python metaclass的理解

python metaclass的理解
1.type,获得变量类型 type(object) -> the object’s type

>>> a = 2
>>> type(a)
'int'>
>>> type(type(a))
'type'>
>>>
>>> class MM(object):
...    def __init__(self):
...       self.a = a
... 
>>> mm = MM()
>>> type(mm)
'__main__.MM'>
>>> isinstance(mm,MM)
True
>>> 
>>>> type(MM)
'type'>
>>> 
  1. type 生成类 type(name, bases, dict) -> a new type

>>> def func(self):
...    print "self.a is ",self.a
... 
>>> MyClass = type('MyClass',(object,),{'func':func,'a':100})
>>> myclass = MyClass()
>>> myclass.func()
self.a is  100
>>> 
  1. 元类,任何一个类建立的时候都需要元类来创建,元类可以用来改变类
    比如下面这个元类就是将类中的变量名改成小写

class UpdateMetaClass(type):
    def __new__(cls,name,bases,attrslist):
        attrs = ((name,value) for name,value in attrslist.items() if not name.startswith("__"))
        lower_attrs = dict((name.lower(),value) for name,value in attrs)
        #return type.__new__(cls,name,bases,lower_attrs)
        return super(UpdateMetaClass,cls).__new__(cls,name,bases,lower_attrs)

class MyClassTest(object):
    __metaclass__ = UpdateMetaClass
    AA = 1000

#AA has been changed to be aa
print MyClassTest.aa


你可能感兴趣的:(python实战)