如何在类的__init__函数中使用函数 - python

在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

python大神给出的解决方案

如果您已阅读第一个示例中的错误消息,则可能为您提供了一个线索。

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