Python类中__new__()方法 和 __init__()方法区别

一.__new__()方法

官方文档:

object.__new__(cls[, ...])

Called to create a new instance of class cls__new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class). The return value of __new__() should be the new object instance (usually an instance of cls).

Typical implementations create a new instance of the class by invoking the superclass’s __new__() method using super().__new__(cls[, ...]) with appropriate arguments and then modifying the newly-created instance as necessary before returning it.

If __new__() returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().

If __new__() does not return an instance of cls, then the new instance’s __init__() method will not be invoked.

__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.

翻译:

用于创建(传递进来的)类cls的新实例。__new__()是一个静态方法,该方法将实例被请求的类作为第一个参数,将类调用时传递的参数作为剩下的参数。__new__()的返回值应该是新的对象实例。(通常是类cls的实例)。

一个类创建新实例的典型实现是使用super().__new__(cls[, ...])语句结合适当的参数来调用父类的__new__方法。如果有需要的话可以在返回实例之前修改实例。

如果__new__()返回类cls的实例,那么该实例的__init__()方法将会像__init__(self[, ...])这样被调用。其中self是新实例,其余的参数是传递给__new__()的参数。

如果__new__()没有返回类cls的实例,那么新实例的__init__()方法将不会被执行。

使用__new__()方法主要是为了允许不可变类型(如int, str, tuple)的子类定制实例。在自定类时,也可以在元类(metaclass)中重写。

扫描二维码关注公众号,回复: 4993316 查看本文章

二.__init__()方法

官方文档:

object.__init__(self[, ...])

Called after the instance has been created (by __new__()), but before it is returned to the caller. The arguments are those passed to the class constructor expression. If a base class has an __init__() method, the derived class’s __init__() method, if any, must explicitly call it to ensure proper initialization of the base class part of the instance; for example: super().__init__([args...]).

Because __new__() and __init__() work together in constructing objects (__new__() to create it, and __init__() to customize it), no non-None value may be returned by __init__(); doing so will cause a TypeError to be raised at runtime.

翻译:

__init__()方法在__new__()方法创建实例后,实例被返回给调用者之前调用。它的参数是传递给构造表达式的那些参数。如果基类具有__init__()方法,那么派生类的__init__()方法(如果有)必须显示调用调用基类的__init_-()方法,如:super().__init__([args...]).

因为__new__()方法和__init__()方法在创建对象时是一起工作的(__new__()创建对象,__init__()自定义对象),而__init__()方法可能会返回一个非None的值,如果真是这样,那么运行时可能会导致TypeError.

三.区别

__new__()用于创建实例,而__init__()则负责初始化实例。

四.参考资料

[1]python官方文档

猜你喜欢

转载自blog.csdn.net/cckavin/article/details/85337109