【问题标题】:Where is __new__ defined in python3? [duplicate]python3中__new__在哪里定义? [复制]
【发布时间】:2018-02-15 01:03:33
【问题描述】:

在 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__“从何而来”?

【问题讨论】:

  • 查看A.__mro__...

标签: python


【解决方案1】:

在 Python 3 中,如果您创建一个类而不添加父类,它会自动从对象继承。你不能再像 Python 2 那样创建旧样式的类了。

例子:

class A: # gets defaulted to class A(object):
    pass

【讨论】:

    【解决方案2】:

    Python3 中的所有类都是 object 的子类,从 mro 中可以看到:

    >>> class A: pass
    ... 
    >>> A.__mro__
    (<class '__main__.A'>, <class 'object'>)
    

    class A(object) 仍然在一些 Python 3 代码中完成,以保持与 Python 2 的向后兼容性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-25
      • 1970-01-01
      • 2016-09-13
      • 1970-01-01
      • 2012-10-13
      • 1970-01-01
      • 2015-01-21
      • 2015-10-24
      相关资源
      最近更新 更多