Python基础之元类详解


Posted in Python onApril 29, 2021

1.python 中一切皆是对象,类本身也是一个对象,当使用关键字 class 的时候,python 解释器在加载 class 的时候会创建一个对象(这里的对象指的是类而非类的实例)

class Student:
    pass
 
s = Student()
print(type(s))  # <class '__main__.Student'>
print(type(Student))  # <class 'type'>

2.什么是元类

元类是类的类,是类的模板
元类是用来控制如何创建类的,正如类是创建对象的模板一样
元类的实例为类,正如类的实例为对象。
type 是python 的一个内建元类,用来直接控制生成类,python中任何 class 定义的类其实是 type 类实例化的对象

3.创建类的两种方法:

# 方法一
class Student:
    def info(self):
        print("---> student info")
 
# 方法二
def info(self):
    print("---> student info")
 
Student = type("Student", (object,), {"info": info, "x": 1})

4.一个类没有声明自己的元类,默认其元类是 type, 除了使用元类 type, 用户也可以通过继承 type 来自定义元类

class Mytype(type):
    def __init__(self, a, b, c):
        print("===》 执行元类构造方法")
        print("===》 元类__init__ 第一个参数:{}".format(self))
        print("===》 元类__init__ 第二个参数:{}".format(a))
        print("===》 元类__init__ 第三个参数:{}".format(b))
        print("===》 元类__init__ 第四个参数:{}".format(c))
 
    def __call__(self, *args, **kwargs):
        print("=====》 执行元类__call__方法")
        print("=====》 元类__call__ args:{}".format(args))
        print("=====》 元类__call__ kwargs:{}".format(kwargs))
        obj = object.__new__(self)  # object.__new__(Student)
        self.__init__(obj, *args, **kwargs)  # Student.__init__(s, *args, **kwargs)
        return obj
 
 
class Student(metaclass=Mytype):  # Student=Mytype(Student, "Student", (), {}) ---> __init__
    def __init__(self, name):
        self.name = name  # s.name=name
 
print("Student类:{}".format(Student))
s = Student("xu")
print("实例:{}".format(s))
 
# 结果:
#     ===》 执行元类构造方法
#     ===》 元类__init__ 第一个参数:<class '__main__.Student'>
#     ===》 元类__init__ 第二个参数:Student
#     ===》 元类__init__ 第三个参数:()
#     ===》 元类__init__ 第四个参数:{'__module__': '__main__', '__qualname__': 'Student', '__init__': <function Student.__init__ at 0x00000269BCA9A670>}
#     Student类:<class '__main__.Student'>
#     =====》 执行元类__call__方法
#     =====》 元类__call__ args:('xu',)
#     =====》 元类__call__ kwargs:{}
#     实例:<__main__.Student object at 0x00000269BC9E8400>

到此这篇关于Python基础之元类详解的文章就介绍到这了,更多相关Python元类详解内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python的dict,set,list,tuple应用详解
Jul 24 Python
python中迭代器(iterator)用法实例分析
Apr 29 Python
详解Python3中yield生成器的用法
Aug 20 Python
python django事务transaction源码分析详解
Mar 17 Python
Python 实现随机数详解及实例代码
Apr 15 Python
python读取excel指定列数据并写入到新的excel方法
Jul 10 Python
Django REST framework视图的用法
Jan 16 Python
pycharm修改界面主题颜色的方法
Jan 17 Python
Python2与Python3的区别实例总结
Apr 17 Python
Python换行与不换行的输出实例
Feb 19 Python
如何使用Pytorch搭建模型
Oct 26 Python
python实现简单聊天功能
Jul 07 Python
教你怎么用Python监控愉客行车程
Django程序的优化技巧
Apr 29 #Python
教你怎么用Python实现多路径迷宫
python3.9之你应该知道的新特性详解
Apr 29 #Python
Python基础之tkinter图形化界面学习
Apr 29 #Python
Django cookie和session的应用场景及如何使用
Apr 29 #Python
Python使用random模块实现掷骰子游戏的示例代码
Apr 29 #Python
You might like
php目录管理函数小结
2008/09/10 PHP
web站点获取用户IP的安全方法 HTTP_X_FORWARDED_FOR检验
2013/06/01 PHP
php 模拟POST提交的2种方法详解
2013/06/17 PHP
PHP迭代器接口Iterator用法分析
2017/12/28 PHP
jquery checkbox,radio是否选中的判断代码
2010/03/20 Javascript
jQuery EasyUI 开源插件套装 完全替代ExtJS
2010/03/24 Javascript
$.getJSON在IE下失效的原因分析及解决方法
2013/06/16 Javascript
JavaScript中instanceof与typeof运算符的用法及区别详细解析
2013/11/19 Javascript
jQuery获取对象简单实现方法小结
2014/10/30 Javascript
使用Angular和Nodejs、socket.io搭建聊天室及多人聊天室
2015/08/21 NodeJs
jQuery实现有动画淡出效果的二级折叠菜单代码
2015/10/17 Javascript
JavaScript如何获取数组最大值和最小值
2015/11/18 Javascript
AngularJS实现textarea记录只能输入规定数量的字符并显示
2016/04/26 Javascript
React Native模块之Permissions权限申请的实例相机
2017/09/28 Javascript
JavaScript Canvas实现验证码
2020/08/02 Javascript
javascript实现日历效果
2019/06/17 Javascript
JS 获取文件后缀,判断文件类型(比如是否为图片格式)
2020/05/09 Javascript
Electron 打包问题:electron-builder 下载各种依赖出错(推荐)
2020/07/09 Javascript
小程序角标的添加及绑定购物车数量进行实时更新的实现代码
2020/12/07 Javascript
python opencv 图像尺寸变换方法
2018/04/02 Python
python实现多线程网页下载器
2018/04/15 Python
python opencv 实现读取、显示、写入图像的方法
2020/06/08 Python
Python如何读写二进制数组数据
2020/08/01 Python
python 如何实现遗传算法
2020/09/22 Python
Django restful framework生成API文档过程详解
2020/11/12 Python
巴基斯坦电子产品购物网站:Home Shopping
2017/09/14 全球购物
宝拉珍选美国官网:Paula’s Choice美国
2018/01/07 全球购物
土耳其新趋势女装购物网站:Addax
2020/01/07 全球购物
土木工程专业大学毕业生求职信
2013/10/13 职场文书
建筑专业自荐信范文
2014/01/05 职场文书
活动总结的格式
2014/05/07 职场文书
夫妻分居协议书范文
2014/11/26 职场文书
2015试用期转正工作总结
2014/12/12 职场文书
工作时间调整通知
2015/04/24 职场文书
详解如何用Python实现感知器算法
2021/06/18 Python
 python中的元类metaclass详情
2022/05/30 Python