10.元类

作者: 芝麻酱的简书 | 来源:发表于2018-08-21 18:21 被阅读7次

    元类的对象是类
    type是python的内建元类

    def __init__(self, name):
        self.name = name
    
    # 创建一个类
    # param1 类名, param2 父类 ,代表是元组 param3 属性
    Foo = type("Foo",(object,), {"name":"bill", "__init__":__init__})
    
    print(Foo.__dict__)
    

    自定义元类:
    class MyType(type):
        def __init__(self,a,b,c):
            print('元类的构造函数执行')
        def __call__(self, *args, **kwargs):
            obj=object.__new__(self)
            self.__init__(obj,*args,**kwargs)
            return obj
    
    
    class Foo(metaclass=MyType):
        def __init__(self,name):
            self.name=name
            
            
    f1=Foo('alex')
    

    相关文章

      网友评论

          本文标题:10.元类

          本文链接:https://www.haomeiwen.com/subject/untjiftx.html