如何在类'__init__函数中使用函数

时间:2015-03-22 21:00:52

标签: python class python-2.7

在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

2 个答案:

答案 0 :(得分:4)

如果您已经阅读了第一个示例中的错误消息,那么可能会给您一些线索。

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

答案 1 :(得分:1)

不确定这是否适合您的用例,但如果tooAhg必须始终为2*ahg,则应使用属性:

class Foo(object):
    def __init__(self, ahg):
        self.ahg = ahg

    @property
    def tooAhg(self):
        return 2 * self.ahg

现在,您可以像访问任何其他类字段(例如tooAhg)一样访问self.tooAhg,而无需在每次更新ahg

时更新它
相关问题