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装饰器
Sep 29 Python
为何人工智能(AI)首选Python?读完这篇文章你就知道了(推荐)
Apr 06 Python
python爬虫爬取幽默笑话网站
Oct 24 Python
Python 实现try重新执行
Dec 21 Python
python实现人机五子棋
Mar 25 Python
浅谈JupyterNotebook导出pdf解决中文的问题
Apr 22 Python
解决python执行较大excel文件openpyxl慢问题
May 15 Python
Keras之fit_generator与train_on_batch用法
Jun 17 Python
在Tensorflow中实现leakyRelu操作详解(高效)
Jun 30 Python
python绘制趋势图的示例
Sep 17 Python
scrapy与selenium结合爬取数据(爬取动态网站)的示例代码
Sep 28 Python
使用python创建股票的时间序列可视化分析
Mar 03 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执行速度全攻略(下)
2006/10/09 PHP
BBS(php &amp; mysql)完整版(八)
2006/10/09 PHP
深入解读php中关于抽象(abstract)类和抽象方法的问题分析
2014/01/03 PHP
PHP+jQuery+Ajax实现用户登录与退出
2015/04/27 PHP
php算法实例分享
2015/07/14 PHP
在WordPress中使用wp_count_posts函数来统计文章数量
2016/01/05 PHP
深入浅析用PHP实现MVC
2016/03/02 PHP
php使用SAE原生Mail类实现各种类型邮件发送的方法
2016/10/10 PHP
PHPCMS手机站伪静态设置详细教程
2017/02/06 PHP
使用apply方法处理数组的三个技巧[译]
2012/09/20 Javascript
jQuery基于当前元素进行下一步的遍历
2014/05/20 Javascript
jquery用data方法获取某个元素上的事件
2014/06/23 Javascript
javascript中数组的定义及使用实例
2015/01/21 Javascript
js实现温度计时间样式代码分享
2015/08/21 Javascript
js游戏人物上下左右跑步效果代码分享
2015/08/28 Javascript
7个jQuery最佳实践
2016/01/12 Javascript
JavaScript下的时间格式处理函数Date.prototype.format
2016/01/27 Javascript
在微信、支付宝、百度钱包实现点击返回按钮关闭当前页面和窗口的方法
2016/08/05 Javascript
javascript数组定义的几种方法
2017/10/06 Javascript
聊聊Vue.js的template编译的问题
2017/10/09 Javascript
Element Backtop回到顶部的具体使用
2020/07/27 Javascript
JS实现小米轮播图
2020/09/21 Javascript
解决python3中自定义wsgi函数,make_server函数报错的问题
2017/11/21 Python
Python实现注册、登录小程序功能
2018/09/21 Python
Python3简单实现串口通信的方法
2019/06/12 Python
Python数据可视化实现多种图例代码详解
2020/07/14 Python
python利用proxybroker构建爬虫免费IP代理池的实现
2021/02/21 Python
Python爬虫+tkinter界面实现历史天气查询的思路详解
2021/02/22 Python
Opencv 图片的OCR识别的实战示例
2021/03/02 Python
日本7net购物网:书籍、漫画、杂志、DVD、游戏邮购
2017/02/17 全球购物
优秀教导主任事迹材料
2014/05/09 职场文书
二年级语文上册复习计划
2015/01/19 职场文书
留学推荐信怎么写
2015/03/26 职场文书
导游词之无锡华莱坞
2019/12/02 职场文书
Pytorch使用shuffle打乱数据的操作
2021/05/20 Python
python 实现体质指数BMI计算
2021/05/26 Python