我刚开始使用 python 的 OOP(如果这是一个愚蠢的问题,请原谅)。我正在使用一个模型,该模型使用一个函数来模拟大气中二氧化碳排放量的衰减。对于每个时间步,类 Emission
的 c_size
属性应该使用 decay
函数减少
我已将代码简化为单次运行,但我一直收到错误:
Traceback (most recent call last):
File "<co2>", line 20, in <module>
x.decay(year=1)
TypeError: decay() got multiple values for argument 'year'
我看不出任何多个值可能来自哪里。我只将一个 int
值传递给代码。
代码是:
import numpy as np
class Emission:
def __init__(self,e_year=0, e_size=0.0):
self.e_year=e_year #emission year
self.e_size=e_size #emission size
self.c_size=[e_size] #current size
def decay(year):
#returns a % decay based on the year since emission 0 = 100% 1 = 93%
# etc. from AR5 WG1 Chapter 8 supplementary material equation 8.SM.10
# using coefficients from table 8.SM.10
term1 = 0.2173
term2 = 0.224*np.exp(-year/394.4)
term3 = 0.2824*np.exp(-year/36.54)
term4 = 0.2763*np.exp(-year/4.304)
out = (term1+term2+term3+term4)*self.e_size
self.c_size.append(out)
print(self.c_size)
x = Emission(e_year=1,e_size=10.0)
x.decay(year=1)
最佳答案
您忘记了 decay
的方法签名中的 self
因此 Python 尝试将实例作为第一个参数(即 year
)插入并且您还显式地传入了 year
- 导致参数冲突。
所以只需将方法定义更改为:
def decay(self, year):
重要的是要认识到方法的第一个参数的名称 self
只是一种约定。如果您将其命名为 year
(尽管您必须为第二个参数找到不同的名称),或者 this
或 the_instance
,它也有效。重要的是当您调用该方法时,该实例作为第一个参数隐式传递给该方法。
所以这也行得通:
def decay(blabla, year):
term1 = 0.2173
term2 = 0.224*np.exp(-year/394.4)
term3 = 0.2824*np.exp(-year/36.54)
term4 = 0.2763*np.exp(-year/4.304)
out = (term1+term2+term3+term4)*blabla.e_size
blabla.c_size.append(out)
print(blabla.c_size)
但这违反了常见的 Python 约定,我不得不用 blabla
更改方法中的所有 self
。
进一步评论:
如果您专门处理标量作为 year
,您可能应该使用 math.exp
而不是 numpy.exp
,因为它是快多了。但是 math.exp
只适用于标量,所以如果你想为 year
使用列表或数组,你必须使用 numpy.exp
。
关于python - 多参数值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46932191/