gpt4 book ai didi

Python 类看不到方法,除非我注释掉 __init__

转载 作者:太空宇宙 更新时间:2023-11-04 09:07:21 25 4
gpt4 key购买 nike

以下代码仅在我注释掉初始化程序时才有效。

class What:
def __init__(self):
pass

def method1(self):
print 'method1'

def main():
b = What()

if hasattr(b,"method1"):
print "b.method1"

b.method1()

main()

如果它没有被注释掉,我会收到错误消息......

Traceback (most recent call last):
File "strange.py", line 17, in <module>
main()
File "strange.py", line 15, in main
b.method1()
AttributeError: What instance has no attribute 'method1'

但是,如果我键入一个相同的方法并调用它,则完全没有问题......

    def method2(self):
print 'method2'

我已经 od -c 文件并且文本中没有奇怪的字符使用 Python 2.7.2

最佳答案

我认为您正在混合使用制表符和空格。

代码每个缩进使用 4 个空格(空格符合 pep8),它工作正常。但是这个

class What:
def __init__(self):
pass

def method1(self):
print 'method1'

def main():
b = What()

if hasattr(b,"method1"):
print "b.method1"

b.method1()

main()

如果您有 method1 的选项卡,Python 会看到什么,这将生成您看到的错误。

关于Python 类看不到方法,除非我注释掉 __init__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19063614/

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