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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值