将类“对象"分类为子类的目的是什么?在Python中? [英] What is the purpose of subclassing the class "object" in Python?
问题描述
所有Python内置都是object
的子类,我也遇到了许多用户定义的类.为什么?类object
的目的是什么?这只是一个空的课,对吧?
All the Python built-ins are subclasses of object
and I come across many user-defined classes which are too. Why? What is the purpose of the class object
? It's just an empty class, right?
推荐答案
简而言之,它设置了免费的魔法小马.
In short, it sets free magical ponies.
长期以来,Python 2.2和更早版本使用旧样式类".它们是类的特定实现,并且有一些限制(例如,您不能对内置类型进行子类化).解决此问题的方法是创建一种新的类样式.但是,这样做将涉及一些向后不兼容的更改.因此,为确保为旧样式类编写的代码仍然有效,创建了object
类以充当所有新样式类的超类.
因此,在Python 2.X中,class Foo: pass
将创建一个旧样式类,而class Foo(object): pass
将创建一个新样式类.
In long, Python 2.2 and earlier used "old style classes". They were a particular implementation of classes, and they had a few limitations (for example, you couldn't subclass builtin types). The fix for this was to create a new style of class. But, doing this would involve some backwards-incompatible changes. So, to make sure that code which is written for old style classes will still work, the object
class was created to act as a superclass for all new-style classes.
So, in Python 2.X, class Foo: pass
will create an old-style class and class Foo(object): pass
will create a new style class.
详细内容请参见Guido的> 在Python 2.2中统一类型和类 .
In longer, see Guido's Unifying types and classes in Python 2.2.
而且,通常,养成使所有类成为新样式的习惯是个好主意,因为有些事情(@property
装饰器是我想到的)不会与旧样式一起使用课.
And, in general, it's a good idea to get into the habit of making all your classes new-style, because some things (the @property
decorator is one that comes to mind) won't work with old-style classes.
这篇关于将类“对象"分类为子类的目的是什么?在Python中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!