Python - 元类编程(type)

    xiaoxiao2023-11-02  175

    一、类是如何产生的
    表面上使用继承创建一个类所有类都直接或间接继承于object 而真正创建类的是typetype type通常的用法–判断对象的类型 但除此之外,它最大的用途是来动态的创建类,当Python扫描到class语法的时候,就会调用type函数进行类的创建type 创建类 type()需要接受三个参数1.类的名称:若不指定也要传入空字符串2.父类:注意以tuple的形式传入,没有也要传入控tuple:(),默认的是object3.绑定的方法或属性:注意以dict的形式传入 # 定义一个父类 class Parent: def foo(self): print('Parent') # 准备一个方法 def say(self): print('hello') # 使用type来创建一个类 Person = type('Person',(Parent,),{'name':'person','say':say}) p = Person() p.foo() p.say() # 结果 Parent hello
    元类
    类 -用来创建对象的模板那么,元类就是创建类的模板type就是一个元类

    就连 object 也是由type创建的 哈哈,就连type自己也是type创建的

    In [1]: type(type) Out[1]: type In [2]: type(object) Out[2]: type In [3]: type(int) Out[3]: type In [4]: type(str) Out[4]: type In [5]: type(bool) Out[5]: type In [6]: type(list) Out[6]: type 有点神奇样 str:用来创建字符串对象的类int:用来创建整数对象的类type:用来创建类对象的类等等…

    示例

    # 继承type class Base(type): def __new__(cls,*args,**kwargs): print('in Base') return super().__new__(cls,*args,**kwargs) class Person(metaclass=Base): def __init__(self,name): self.name = name p = Person('tom') # 控制台 in Base
    最新回复(0)