关于python的元类

时间:2023-03-09 03:06:25
关于python的元类
当你创建一个类时:
class Foo(Bar):
pass

Python做了如下的操作:

Foo中有__metaclass__这个属性吗?如果是,Python会在内存中通过__metaclass__创建一个名字为Foo的类对象(我说的是类对象,请紧跟我的思路)。如果Python没有找到__metaclass__,它会继续在Bar(父类)中寻找__metaclass__属性,并尝试做和前面同样的操作。如果Python在任何父类中都找不到__metaclass__,它就会在模块层次中去寻找__metaclass__,并尝试做同样的操作。如果还是找不到__metaclass__,Python就会用内置的type来创建这个类对象。

关于什么是类元,下面这篇文章很完美了,不需要修改!

http://blog.jobbole.com/21351/

在元类中使用带标签的描述符

 class Descriptor(object):
def __init__(self):
# notice we aren't setting the label here
self.label = None def __get__(self, instance, owner):
print('__get__. Label = %s' % self.label)
return instance.__dict__.get(self.label, None) def __set__(self, instance, value):
print('__set__')
instance.__dict__[self.label] = value class DescriptorOwner(type):
def __new__(cls, name, bases, attrs):
# find all descriptors, auto-set their labels
for n, v in attrs.items():
if isinstance(v, Descriptor):
v.label = n #这里的v.相当于x
return super(DescriptorOwner, cls).__new__(cls, name, bases, attrs) class Foo(object):
__metaclass__ = DescriptorOwner
x = Descriptor()

结果为:

f = Foo()
f.x = 10
print(f.x)
第6行:__get__(self, instance, owner):中的self代表的是实例x,instance是实例f,owner代表类别Foo;
第10行:__set__(self, instance, value)中的self代表的是实例x,instance是实例f,val值为10。