在 Python 3.x 中继承 Python 的对象是必要的还是有用的?

在旧的 Python 版本中,当您创建一个类时,它可以从 object继承,据我所知,object是一个特殊的内置 Python 元素,它允许您的类成为一个新样式的类。

那么新版本(> 3.0和2.6)呢?我在谷歌上搜索了 object类,但是我得到了很多结果(原因显而易见)。

26138 次浏览

You don't need to inherit from object to have new style in python 3. All classes are new-style.

I realise that this is an old question, but it is worth noting that even in python 3 these two things are not quite the same thing.

If you explicitly inherit from object, what you are actually doing is inheriting from builtins.object regardless of what that points to at the time.

Therefore, I could have some (very wacky) module which overrides object for some reason. We'll call this first module "newobj.py":

import builtins


old_object = builtins.object  # otherwise cyclic dependencies


class new_object(old_object):


def __init__(self, *args, **kwargs):
super(new_object, self).__init__(*args, **kwargs)
self.greeting = "Hello World!"


builtins.object = new_object  #overrides the default object

Then in some other file ("klasses.py"):

class Greeter(object):
pass


class NonGreeter:
pass

Then in a third file (which we can actually run):

import newobj, klasses  # This order matters!


greeter = klasses.Greeter()
print(greeter.greeting)  # prints the greeting in the new __init__


non_greeter = klasses.NonGreeter()
print(non_greeter.greeting) # throws an attribute error

So you can see that, in the case where it is explicitly inheriting from object, we get a different behaviour than where you allow the implicit inheritance.