Wil*_*ill 1 python oop class function python-3.x
我刚开始使用OOP进行python(如果这是一个愚蠢的问题,请原谅我).我正在使用一个模型,该模型使用一个函数来模拟大气中二氧化碳排放的衰减.对于每个时间步,应使用该函数减少c_size类的属性Emissiondecay
我已将代码简化为单次运行,但我不断收到错误:
Traceback (most recent call last):
File "<co2>", line 20, in <module>
x.decay(year=1)
TypeError: decay() got multiple values for argument 'year'
Run Code Online (Sandbox Code Playgroud)
我无法看到任何多个值可能来自哪里.我只是将一个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)
Run Code Online (Sandbox Code Playgroud)
你忘记了self方法签名,decay因此Python试图将实例作为第一个参数插入(这是year)并且你也year明确地传入- 导致参数冲突.
所以只需将方法定义更改为:
def decay(self, year):
Run Code Online (Sandbox Code Playgroud)
重要的是要意识到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)
Run Code Online (Sandbox Code Playgroud)
但这违反了常见的Python惯例,我不得不改变方法中的所有selfs blabla.
进一步评论:
如果你只是处理标量,year你应该使用math.exp而不是numpy.exp,因为它更快.但math.exp只适用于标量,所以如果你想使用列表或数组,year你必须使用numpy.exp.