好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

python面向对象--元类

一个类没有声明自己的元类,默认他的元类就是type,除了使用内置元类type,我们也可以通过继承type来自定义元类,然后使用metaclass关键字参数为一个类指定元类
class Foo:
    def __init__(self):
        pass

f1=Foo()#f1是通过Foo实例化的对象

#print(type(f1))
print(type(Foo))
print(Foo.__dict__)

def __init__(self,name,age):
    self.name=name
    self.age=age

Ffo=type("Ffo",(object,),{‘x‘:1,"__init__":__init__})
print(Ffo)
print(Ffo.__dict__)

f1=Ffo("alex",20)
print(f1.__dict__)
print(f1.name)  #自定制元类
class MyType(type):     def __init__(self,a,b,c):         print("元类的函数执行")         print(self)         # print(a)         # print(b)         # print(c)  #__call__对象后面加括号,触发执行。注:构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()
    def __call__(self, *args, **kwargs):        print("=======>")        print(args,kwargs)        obj=object.__new__(self)#----->f1生成对象        self.__init__(obj,*args)        return objclass Foo(metaclass=MyType):# Foo=MyType(4个参数) -->__init__    --->MyType(Foo,‘Foo‘,(object,),{})    def __init__(self,name):        self.name=nameprint(Foo)f1=Foo("alex")#Foo()执行对象的call方法print(f1.name)# print(f1.name)# print(f1.__dict__)

查看更多关于python面向对象--元类的详细内容...

  阅读:20次