关于python中__new__ 的一些疑惑

新手上路,请多包涵
在我自己写的类中,如果没有实现__new__方法的话,而且仅仅继承了object类,是否由object提供 __new__方法的默认实现。
另外,如果自己写的类继承了其他父类类(非object类),而该父类实现了__new__方法,那么子类用的是该父类的new方法还是object类的new方法。
class A(object):
    pass

class A(object):
    def __new__(cls):
        pass
        
clas B(A):
    pass
阅读 4.1k
3 个回答

python在查找类方法时会依照深度优先的方式沿着继承链往父类寻找,子类没有的函数会自动找父类,父类没有就找父类的父类直到找到为止.所有其他支持面向对象的语言的继承也是这样查找的.
根据第一条,你的子类无new函数,父类有new函数那么在new 子类的时候当然会调用父类的new,至于父类会不会调用object的new那要看父类是不是继承了object.
你可以搜索python mro查找更多的资料

Python中类有两种,如果定义class的时候继承了object那么就是新式类,如果没有继承object则为旧式类。

new 方法的返回值就是类的实例对象,这个实例对象会传递给 init 方法中定义的 self 参数,以便实例对象可以被正确地初始化。

所以class 在实例化时一定会调用__new__方法,至于调用谁的方法,请继续往下看。

class 在继承后,若复写了父类的方法,父类的方法将不会被调用此时只会调用子类本身的方法,这个不是Python,这是面向对象的思想。

python支持多继承,在多继承情况下:

若子类没有该方法则,新式类遵循广度优先查找,旧式类遵循深度优先查找,若所有父类都没有该方法,则向上抛出AttributeError异常。

new就是一个特殊的方法,引用 Zen Of Python中的一句话:

import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!


共勉

print打印一下不就知道了吗

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题