所有 Python 类都应该扩展对象吗? [英] Should all Python classes extend object?
问题描述
我发现以下两种方法都有效:
class Foo():定义一个(自我):打印你好"类 Foo(对象):定义一个(自我):打印你好"
所有 Python 类都应该扩展对象吗?不扩展对象有什么潜在的问题吗?
在 Python 2 中,不从 object
继承将创建一个旧式的类,除其他效果外,它会导致 输入
给出不同的结果:
对比
<预><代码>>>>类 Bar(object): 通过...>>>类型(酒吧())<class '__main__.Bar'>多重继承的规则也是不同的,我什至不会试着在这里总结一下.我见过的所有关于 MI 的优秀文档都描述了新式类.
最后,旧式类在 Python 3 中消失了,从 object
继承变得隐含.所以,除非你需要向后兼容旧软件,否则总是喜欢新风格的类.
I have found that both of the following work:
class Foo():
def a(self):
print "hello"
class Foo(object):
def a(self):
print "hello"
Should all Python classes extend object? Are there any potential problems with not extending object?
In Python 2, not inheriting from object
will create an old-style class, which, amongst other effects, causes type
to give different results:
>>> class Foo: pass
...
>>> type(Foo())
<type 'instance'>
vs.
>>> class Bar(object): pass
...
>>> type(Bar())
<class '__main__.Bar'>
Also the rules for multiple inheritance are different in ways that I won't even try to summarize here. All good documentation that I've seen about MI describes new-style classes.
Finally, old-style classes have disappeared in Python 3, and inheritance from object
has become implicit. So, always prefer new style classes unless you need backward compat with old software.
这篇关于所有 Python 类都应该扩展对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!