'''什么是元类:元类是类的类,是类的模板;元类是用来控制如何创建类的,正如类是创建对象的模板一样;元类的实例为类,正如类的实例为对象(f1对象是Foo类的 一个实例,Foo类是type类的一个实例);type是python的一个内建元类,用来直接控制生成类,python中任何class定义的类其实都是type类实例化的对象''' # class创建类的第一种方式 # class Foo: # ... # # f1 = Foo() # print(type(f1)) # <class '__main__.Foo'> # print(type(Foo)) # <class 'type'> # type创建类的第二种方式 # def __init__(self, name, age): # self.name = name # self.age = age # # def test(self): # # print('test函数') # return 'test' # # Cls = type('Cls', (object,), {'x': 1, '__init__': __init__, 'test': test}) # 类名=type('字符串name', (父类,), {'属性': 属性指})--->type(cls, what, bases=None, dict=None),cls不用写,自动传 # print(Cls) # <class '__main__.Cls'> # print(Cls.x) # 1 # f2 = Cls('alex', 18) # 实例化过程 # print(f2.x, f2.name, f2.age, f2.test()) # 调用类属性 '''一个类没有声明自己的元类,默认他的元类就是type,除了使用元类type,用户也可以通过继承type来自定义元类''' # 默认继承元类type class City(metaclass=type): # City = type('City', (object,), {'__init__': __init__}) def __init__(self, name): self.name = name c1 = City('赣州') # 自定制元类 class Mytype(type): # 这里必须继承type类 def __init__(cls, name, meta, dic): print(cls) # <class '__main__.Hot'> print(name) # 'Hot' print(meta) # () print(dic) # {'__module__': '__main__', '__qualname__': 'Hot', '__init__': <function Hot.__init__ at 0x0000028E0B932C10>} def __call__(cls, *args, **kwargs): # cls为Hot,*args和**kwargs为参数 # print('执行Mytype的call方法') obj = object.__new__(cls) # 由object顶级类产生一个对象--->object.__new__(Hot)--->h1 cls.__init__(obj, *args, **kwargs) # cls是一个类,类调用类属性时self也需要传参;参数怎么传进来的,可以原封不动怎么传回去--->下一步会跳到类Hot的__init__,Hot.__init__(h1, *args, **kwargs) return obj class Hot(metaclass=Mytype): # 先触发这一步操作:Hot = Mytype(Hot, 'Hot', (object,), {'类属性': '类属性值'})--->实例化触发__init__ def __init__(self, name): self.name = name # h1.name = name h1 = Hot('hh') # Hot('hh')加括号执行,运行的就是Mytype下的__call__方法 # print(h1) # Mytype下的__call__方法没有返回值(只有print操作的时候),所以h1为None print(h1.__dict__) print(Hot.__dict__)