从 Python 3.x 中的 Python 对象继承是否有必要或有用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1238606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:45:22  来源:igfitidea点击:

Is it necessary or useful to inherit from python's object in Python 3.x?

pythonpython-3.x

提问by thomas

In older python version when you create a class in python, it can inherit from objectwhich is as far I understand a special built-in python element that allow your object to be a new-style object.

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

What about newer version (> 3.0 and 2.6)? I googled about the class object but I get so much result (for an obvious reasons). Any hint?

较新的版本(> 3.0 和 2.6)怎么样?我在 google 上搜索了 class 对象,但得到了很多结果(出于明显的原因)。任何提示?

Thank!

感谢!

采纳答案by SilentGhost

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

object在python 3中你不需要继承来拥有新的风格。所有的类都是新风格的。

回答by Philip Adler

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.

我意识到这是一个老问题,但值得注意的是,即使在 python 3 中,这两件事也不完全相同。

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

如果您显式继承自object,那么您实际所做的就是继承自 ,builtins.object而不管它当时指向什么。

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

因此,我可以有一些(非常古怪的)模块由于某种原因覆盖对象。我们将第一个模块称为“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"):

然后在其他一些文件(“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.

所以你可以看到,在它显式继承自对象的情况下,我们得到的行为与你允许隐式继承的行为不同。