gpt4 book ai didi

python - 类属性中的属性错误

转载 作者:行者123 更新时间:2023-12-01 03:29:37 25 4
gpt4 key购买 nike

我编写了一个名为cl的类:

class cl :
def __int__(self):
self.a = 0


def increment(self):
self.a +=1

def print_a(self):
print ("value : "+str(self.a))

我编写了另一个名为test的类。但是,我在调用方法时遇到错误。

 from cl import *

class test :
def __int__(self):
self.b = 0
self.c = cl()


def main(self):
self.c.increment()
self.c.print_a()
self.c.increment()
self.c.print_a()

d = test()
d.main()

我得到的是这样的:

 Traceback (most recent call last):
File "test_file.py", line 19, in <module>

d.main()
File "test_file.py", line 12, in main
self.c.increment()
AttributeError: test instance has no attribute 'c'

任何人都可以解释为什么会发生这种情况以及我的代码有什么问题吗?我是一名高中生。你能给我解释一下吗?你能帮我解决这个问题吗?

最佳答案

您将 __init____int__ 拼写错误:

class cl :
def __int__(self):
self.a = 0

应该是

class cl :
def __init__(self):
self.a = 0

请注意,在 test 类中包含 main 方法实际上是 Python 中的反模式;的形式

def main():
...

if __name__ == "__main__":
main()

是首选并且更Pythonic。

有关 if __name__ == "__main__" 模式的一些引用,请参阅:

关于python - 类属性中的属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41072377/

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