python - __init__ 作为构造函数?

标签 python constructor initialization

Dive into Python -

It would be tempting but incorrect to call this the constructor of the class. It's tempting, because it looks like a constructor (by convention, __init__ is the first method defined for the class), acts like one (it's the first piece of code executed in a newly created instance of the class), and even sounds like one (“init” certainly suggests a constructor-ish nature). Incorrect, because the object has already been constructed by the time __init__ is called, and you already have a valid reference to the new instance of the class.

引用建议将 __init__ 作为 构造函数 调用是不正确的,因为在调用 __init__ 时对象已经被构造。但!我一直认为 constructor 仅在构造对象后才被调用,因为它本质上是用于初始化实例的数据成员,如果对象不这样做就没有意义constructor 被调用时是否存在? (来自 C++/Java 背景)

最佳答案

如果你有一个类 Foo 那么:

  • Foo()构造函数
  • Foo.__init__()初始化器
  • Foo.__new__()分配器

Python 对象的构造只是分配一个新实例,然后初始化该实例。

关于python - __init__ 作为构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6578487/

相关文章:

c++ - 对象 std::string 出错

python - Selenium Headless Chrome 和语言设置

Python - 需要遍历目录以查找 TXT 文件

python - 计算字符串出现次数的最快方法

c# - 是否可以将泛型类型限制为接口(interface)、new()?

c++ - 两步到一步初始化和错误处理

java - 枚举正在尝试通过不存在的公共(public)初始化程序来初始化自身

initialization - init() 和dispatch_sync 的难题

c++ - C - 字符数组初始化

python - 适用于 Python 3 的 Jupyter Notebook 中出现 ModuleNotFoundError,但不适用于 Python 2 (Mac OSX)