Python - 元类编程(type)

一、类是如何产生的
  • 表面上使用继承创建一个类
  • 所有类都直接或间接继承于object
    而真正创建类的是type
  • type
    type通常的用法–判断对象的类型
    但除此之外,它最大的用途是来动态的创建类,当Python扫描到class语法的时候,就会调用type函数进行类的创建
  • type 创建类
    • type()需要接受三个参数
    • 1.类的名称:若不指定也要传入空字符串
    • 2.父类:注意以tuple的形式传入,没有也要传入控tuple:(),默认的是object
    • 3.绑定的方法或属性:注意以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
发布了53 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42874994/article/details/90549357