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实现爬取需要登录的网站完整示例
Aug 19 Python
Python使用Matplotlib模块时坐标轴标题中文及各种特殊符号显示方法
May 04 Python
django manage.py扩展自定义命令方法
May 27 Python
Sanic框架基于类的视图用法示例
Jul 18 Python
Flask框架Jinjia模板常用语法总结
Jul 19 Python
Python中出现IndentationError:unindent does not match any outer indentation level错误的解决方法
Apr 18 Python
python爬取微信公众号文章的方法
Feb 26 Python
Python:Numpy 求平均向量的实例
Jun 29 Python
python多继承(钻石继承)问题和解决方法简单示例
Oct 21 Python
Flask response响应的具体使用
Jul 15 Python
Python实现日志实时监测的示例详解
Apr 06 Python
python游戏开发Pygame框架
Apr 22 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
ajax缓存问题解决途径
2006/12/06 PHP
让的PHP代码飞起来的40条小技巧(提升php效率)
2010/04/12 PHP
PHP合并静态文件详解
2014/11/14 PHP
PHP-X系列教程之内置函数的使用示例
2017/10/16 PHP
PDO::beginTransaction讲解
2019/01/27 PHP
Yii2.0框架模型多表关联查询示例
2019/07/18 PHP
JavaScript实现星级评分
2017/01/12 Javascript
Vue实例简单方法介绍
2017/01/20 Javascript
JS打印彩色菱形的实例代码
2018/08/15 Javascript
vue中接口域名配置为全局变量的实现方法
2018/09/20 Javascript
微信小程序开发之左右分栏效果的实例代码
2019/05/20 Javascript
Vue组件通信入门之Provide和Inject机制
2019/12/29 Javascript
原生js实现弹窗消息动画
2020/11/20 Javascript
jquery实现穿梭框功能
2021/01/19 jQuery
python中global用法实例分析
2015/04/30 Python
浅析Python中的join()方法的使用
2015/05/19 Python
Python for循环生成列表的实例
2018/06/15 Python
python实现给微信指定好友定时发送消息
2019/04/29 Python
Python中使用pypdf2合并、分割、加密pdf文件的代码详解
2019/05/21 Python
通过cmd进入python的实例操作
2019/06/26 Python
python Yaml、Json、Dict之间的转化
2020/10/19 Python
牦牛毛户外探险服装:Kora
2019/02/08 全球购物
如何整合JQuery和Prototype
2014/01/31 面试题
用Python写一个for循环的例子
2016/07/19 面试题
大专生自荐信
2013/10/04 职场文书
司马光教学反思
2014/02/01 职场文书
九年级语文教学反思
2014/02/04 职场文书
客服部工作职责范本
2014/02/14 职场文书
学术会议主持词
2014/03/17 职场文书
竞选体育委员演讲稿
2014/04/26 职场文书
单位个人查摆问题及整改措施
2014/10/28 职场文书
保研推荐信格式
2015/03/25 职场文书
2015年上半年物业工作总结
2015/03/30 职场文书
酒店工程部主管岗位职责
2015/04/16 职场文书
惊涛骇浪观后感
2015/06/05 职场文书
《雪地里的小画家》教学反思
2016/02/16 职场文书