Skip to main content
 首页 » 编程设计

python之python3中的__new__在哪里定义的

2025年05月04日14unruledboy

<分区>

在 Python 2 中:

>>> class A: 
...  pass 
...  
>>> A.__new__ 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
AttributeError: class A has no attribute '__new__' 
>>> class A(object): 
...  pass 
...  
>>> A.__new__ 
<built-in method __new__ of type object at 0x1062fe2a0> 

结论:object包含__new__,子类继承该方法。

在 Python 3 中:

>>> class A: 
...  pass 
...  
>>> A.__new__ 
<built-in method __new__ of type object at 0x100229940> 

__new__ 是我们类中定义的方法,没有任何继承。这是如何运作的? __new__“来自”哪里?