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

标签 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

最佳答案

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

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/

相关文章:

python - 从python中的视频中提取音频

python - 在 gremlin-python 中使用合并和值之间的组合失败

java - 获取类的所有实例

c++ - 在 C++ 中删除类之间的循环依赖

java - 从外部 Action 监听器访问 Jtextfield

python - python - 如何在python的另一个模块中排除ValueError?

python - 我无法使用 pyodbc 从 MySQL 正确打印字符

python - 协议(protocol)错误,得到 "H"作为回复类型字节

python - 如何优雅地对 Pandas 中的一系列列表进行热编码

multithreading - 在计算时保持GIF动画运行