在 Python 2.7 中我有这个类定义:
class foo:
def __init__(self,ahg):
self.ahg=ahg
def oaf(arg):
return arg*2
self.tooAhg=self.oaf(self.ahg)
在控制台我做出以下声明
>>> bibi=foo(1)
>>> vars(bibi)
{'ahg': 1}
我不知道为什么 vars(bibi)
不返回 {'ahg': 1, 'tooAhg': 2}
。请帮忙!此外,
另一个不成功的策略是:
class foo:
def __init__(self,ahg):
self.ahg=ahg
self.tooAhg=self.oaf()
def oaf(self):
return self.ahg*2
最佳答案
如果您已阅读第一个示例中的错误消息,那么这可能会给您提供线索。
self.tooAhg=self.oaf(self.ahg)
AttributeError: foo instance has no attribute 'oaf'
函数名称是oaf
,而不是self.oaf
。
class foo:
def __init__(self,ahg):
self.ahg=ahg
def oaf(arg):
return arg*2
self.tooAhg=oaf(self.ahg)
bibi=foo(1)
print vars(bibi)
给予:
{'tooAhg': 2, 'ahg': 1}
如果你想让函数oaf
成为对象的一个属性,那么:
self.oaf = oaf
关于python - 如何在类的 __init__ 函数中使用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29199792/