【发布时间】:2018-04-06 12:43:02
【问题描述】:
我刚开始使用 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)
【问题讨论】:
-
FWIW,一旦你将
self添加到Emission.decay的方法签名中,你的代码就会打印出[10.0, 9.3452514335147363]。你可能想知道为什么 Python 没有在这里给出更有用的错误信息。好吧,它不能——self这个名字没有什么特别之处,它只是一个用来指代实例的传统名称,Python 允许你随意命名它。 -
谢谢 - 这正是我所期待的。它仍然是 WIP,但我需要能够显示每个对象随时间衰减的历史 - 因此需要一个列表
标签: python python-3.x function class oop