博客
关于我
metaclass
阅读量:794 次
发布时间:2023-02-08

本文共 2262 字,大约阅读时间需要 7 分钟。

基本常识

1.对象是类创建,创建对象时候类的__init__方法自动执行,对象()执行类的 __call__ 方法2.类是type创建,创建类时候type的__init__方法自动执行,类() 执行type的 __call__方法(类的__new__方法,类的__init__方法)# 第0步: 执行type的 __init__ 方法【类是type的对象】class Foo:    def __init__(self):        pass    def __call__(self, *args, **kwargs):        pass# 第1步: 执行type的 __call__ 方法#        1.1  调用 Foo类(是type的对象)的 __new__方法,用于创建对象。#        1.2  调用 Foo类(是type的对象)的 __init__方法,用于对对象初始化。obj = Foo()# 第2步:执行Foodef __call__ 方法obj()

示例一

class MyType(type):    def __init__(self, *args, **kwargs):        print('MyType创建类',self)        super(MyType, self).__init__(*args, **kwargs)    def __call__(self, *args, **kwargs):        obj = super(MyType, self).__call__(*args, **kwargs)        print('类创建对象', self, obj)        return objclass Foo(object,metaclass=MyType):    user = 'ctz'    age = 18obj = Foo()
View Code

结果:

MyType创建类 
类创建对象
<__main__.Foo object at 0x0000024858243470>

示例二:

class MyType(type):    def __init__(self, *args, **kwargs):        print('MyType',self,'----')        super(MyType, self).__init__(*args, **kwargs)    def __call__(cls, *args, **kwargs):        v = dir(cls)        obj = super(MyType, cls).__call__(*args, **kwargs)        print('MyType',cls,obj,'****')        return objclass Foo(MyType('MyType', (object,), {})):    user = 'ctz'    age = 18obj = Foo()
View Code

结果

MyType 
----MyType
----MyType
<__main__.Foo object at 0x0000025A92BB36D8> ****

示例三:(查看wtforms源码可知,实例化Form就是通过这种方法做的,此外这种方式可以实现单例模式)

class MyType(type):    def __init__(self, *args, **kwargs):        print(self,'------')        super(MyType, self).__init__(*args, **kwargs)    def __call__(cls, *args, **kwargs):        v = dir(cls)        obj = super(MyType, cls).__call__(*args, **kwargs)        print(cls,obj,'****')        return objdef with_metaclass(arg,base):    return MyType('MyType', (base,), {})class Foo(with_metaclass(MyType,object)):    user = 'ctz'    age = 18obj = Foo()
View Code

结果:

------
------
<__main__.Foo object at 0x000001FBD9E63710> ****

 后面由于在公司做分享,没什么分享的,就分享了元类 自己整理了一篇在简书上链接如下:https://www.jianshu.com/p/f3de04763481

转载于:https://www.cnblogs.com/ctztake/p/8259785.html

你可能感兴趣的文章
mamp环境下navicat无法链接本地mysql
查看>>
Managing CentOS/RHEL kernel modules.
查看>>
Mangoa-Auth/芒果自助多应用企业级授权系统拥有盗版入库、远程更新等功能
查看>>
MangoDB4.0版本的安装与配置
查看>>
Manjaro 24.1 “Xahea” 发布!具有 KDE Plasma 6.1.5、GNOME 46 和最新的内核增强功能
查看>>
Manjaro 24.2 “Yonada” 发布:尖端功能与精美界面再度进化
查看>>
Manjaro Linux 推出新不可变版本:扩展产品范围,开放社区反馈和测试
查看>>
Manual write code to record error log in .net by Global.asax
查看>>
map 函数返回的列表在使用一次后消失
查看>>
Map 遍历取值及jstl的取值
查看>>
Mapbox GL示例教程【目录】-- 已有80篇
查看>>
Mapbox TOKML:将GeoJSON转换为KML的开源工具
查看>>
Mapped Statements collection already contains value for*
查看>>
mapper.xml中mapper找不到问题
查看>>
Mapper映射文件传参(数组/集合)与#{}和${} 区别
查看>>
mapping文件目录生成修改
查看>>
MapReduce Java API-使用Partitioner实现输出到多个文件
查看>>
MapReduce Java API-多输入路径方式
查看>>
MapReduce与HDFS企业级优化
查看>>
MapReduce分布编程模型之函数式编程范式
查看>>