gpt4 book ai didi

python - 未实现的 __init__()

转载 作者:行者123 更新时间:2023-11-28 22:39:37 26 4
gpt4 key购买 nike

我正在查看一些包含拼写错误的 __init__() 函数的代码(它总共有 3 个下划线,而不是 4 个)。我意识到当一个对象找不到合适的 __init__() 时,我真的不知道在 Python 中会发生什么。

是否有自动插入的默认初始化程序?是否有默认的 __new__ 被调用?为什么带参数的构造函数会失败?

class TestClass(object):
def do_something(self):
print("Hello From TestClass!")

# What is called here?
instance = TestClass()
instance.do_something()

# Why does this fail?
argument = 100
instance = TestClass(argument)

最佳答案

Is there a default initializer that is inserted automatically?

是的。除非被覆盖/继承,否则每个类都有一个默认的虚拟构造函数。

Is there a default __new__ that gets called?

是的。同样,默认情况下,除了实际创建对象和设置其类型外,它不会做太多事情。

Why does a constructor with arguments fail?

因为默认构造函数不带参数也不做任何事情。

关于python - 未实现的 __init__(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34549202/

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