简体   繁体   English

旧样式类,新样式类和元类

[英]Old-style classes, new-style classes and metaclasses

In Python 2.x, all new-style classes inherit from object implicitly or explicitly. 在Python 2.x中,所有新式类都隐式或显式地从object继承。 Then look at this: 然后看这个:

>>> class M(type):
...     pass
...
>>> class A:
...     __metaclass__ = M
...
>>> class B:
...     pass
...
>>> a = A()
>>> b = B()
>>> type(A)
<class '__main__.M'>
>>> type(a)
<class '__main__.A'>

Does this mean A is a new-style class? 这是否意味着A是一种新型类? But A doesn't inherit from object anyway, right? 但是A仍然不会从object继承,对吗?

>>> type(B)
<class 'classobj'>
>>> type(b)
<type 'instance'>

OK, B is a classic class, isn't it? 好吧, B是经典班,不是吗?

>>> isinstance(A, object)
True
>>> isinstance(B, object)
True

why are instances of both A and B instances of object ? 为什么object AB实例都是实例?

If B is an instance of object , then type(B) wouldn't be classobj , right? 如果Bobject的实例,则type(B)不会是classobj ,对吧?

About metaclasses you may read here: http://docs.python.org/reference/datamodel.html#customizing-class-creation . 关于元类,您可以在这里阅读: http : //docs.python.org/reference/datamodel.html#customizing-class-creation Generally metaclasses are intended to work with new style classes. 通常,元类旨在与新样式类一起使用。 When you write: 当你写:

class M(type):
    pass

and you use: 而您使用:

class C:
    __metaclass__ = M

you will create a new style object because the way M is defined (default implementation uses type to create a new-style class). 您将创建一个新样式对象,因为定义了M的方式(默认实现使用type来创建新样式类)。 You could always implement you own metaclass that would create old-style classes using types.ClassType . 您始终可以实现自己的元类,该元类将使用types.ClassType创建老式的类。

About slots you may read here http://docs.python.org/release/2.5.2/ref/slots.html , a fragment: 关于插槽,您可以在此处http://docs.python.org/release/2.5.2/ref/slots.html中阅读片段:

By default, instances of both old and new-style classes have a dictionary for attribute storage. 默认情况下,新旧类的实例都具有用于属性存储的字典。

For new-style classes you may add __slots__ , then the per-object dictionary will not be created. 对于新型类,您可以添加__slots__ ,然后将不会创建每个对象的字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM