gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:51:52 25 4
gpt4 key购买 nike

在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com