理解Python的元类

2024-06-15 02:20
文章标签 python 理解 元类

本文主要是介绍理解Python的元类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.type()函数

type 函数是一个内置函数,用来获取一个对象的类型。它可以接受一个参数,返回这个参数的数据类型。type也可以用来创建类,type就是元类

x=333
list=["ab"]
tuple = (1, "a", True, 3.14)
dict = {'name': 'Alice','age': 25,'is_student': False
}
print(type(x)) # <class 'int'>
print(type(list)) # <class 'list'>
print(type(tuple)) # <class 'tuple'>
print(type(dict))  # <class 'dict'>

2. type(对象)和type(类)

class Student:def __init__(self,name,age) :self.name=nameself.age=agelu=Student("LuMingfei",15)print( type(lu) )       # <class '__main__.Student'>
print( type(Student) )  # <class 'type'>
print( lu.__class__ )   # <class '__main__.Student'>
print( Student.__class__ ) # <class 'type'>print( type(lu)==lu.__class__ ) # True
print( type(Student)==Student.__class__ ) # True
print( type(type) )
"""
<class 'type'>
"""

 ​​

for x in int, float, dict, list, tuple:print(type(x))"""
<class 'type'>
<class 'type'>
<class 'type'>
<class 'type'>
<class 'type'>
"""

3.type() —— type(<name>, <bases>, <dct>)

3.1 example1: type()定义类,创建类

name:指定类名

base:指定一个tuple,指定父类

dct:类体的定义

Student = type('Student', (), {})
Lu = Student()print( type(Student) ) # <class 'type'>
print( type(Lu) )       # <class '__main__.Student'>

3.2 example2:子类继承父类,定义子类的常规写法

class Person:def __init__(self, name):self.name = nameclass Student(Person):def __init__(self, name, score):super().__init__(name)self.score=scoreLu = Student('LuMingfei', 120)print(Lu.name," ",Lu.score)      # LuMingfei   120
print(type(Lu))     # <class '__main__.Student'>
print(Lu.__class__) # <class '__main__.Student'>
print(Lu.__class__.__base__)    # <class '__main__.Person'>

3.3 example3:type()写法:定义子类,创建子类,子类继承父类 

# 父类
class Person:def __init__(self, name):self.name = name# 定义student的初始化函数,Student继承了Person类
def student_init(self, name, score):super(Student, self).__init__(name)self.score = score#用字典的形式,定义student的方法和变量
StudentDict = {'__init__': student_init,'score': None
}#子类 type(类名,父类,方法和变量)
Student = type('Student', (Person,), StudentDict)Lu = Student('LuMingfei', 85)print(Lu.name," ",Lu.score)      # LuMingfei   85
print(type(Lu))     # <class '__main__.Student'>
print(Lu.__class__) # <class '__main__.Student'>
print(Lu.__class__.__base__)    # <class '__main__.Person'>

4.自定义元类

4.1 类创建对象的相关方法

__new__()和__init__()

类的new()方法生出了对象,new()创建当前类对应的对象

Student的 new() 方法生出了 lu对象,具体来说,object按照Student的模板生出了lu对象

Student的 init() 填充 lu对象的属性

class Student:def __new__(cls,*args) :print(cls," ",args) # <class '__main__.Student'>   ('LuMinfei', 120)"""因为Student的父类是object,class Student: 其实是 class Student(object):所以obj=object.__new__(cls)可以替换成obj=super().__new__(cls)"""# obj=super().__new__(cls)obj=object.__new__(cls)  # 根据类(cls)创建了一个 对象(obj)print(obj)          # <__main__.Student object at 0x000001C2DF270FA0>return objdef __init__(self,name,score):print(self)         # <__main__.Student object at 0x000001C2DF270FA0>self.name=nameself.score=score"""__new__()中的obj和__init__()的self的地址相同,__new__()先执行,然后到__init__()执行__new__():根据 类(cls)创建出对象(obj,也是init()中的self)__init__():给对象(self)初始化属性"""
lu=Student("LuMinfei",120)

也可以这样写,*args改为**kwargs,元组形式的参数改为字典形式的参数

class Student:def __new__(cls,**kwargs) :# <class '__main__.Person'>   {'name': 'LuMingfei'}print(cls," ",kwargs) obj=object.__new__(cls)return objdef __init__(self,name,score):self.name=nameself.score=scoredata_dict = {"name": "LuMingfei","score":120}
lu = Student(**data_dict)
print(lu.name,lu.score)
"""
我靠,**kwargs接受参数,这样写传参数也行
"""
lu=Student(name="LuMingfei",score=135)
print(lu.name,lu.score)

__call__()

__call__():的调用跟new()和 init()没什么关系

对象() 调用 类的__call__()

class Student:def __new__(cls,*args) :# cls是 <class '__main__.Student'>obj=object.__new__(cls)# obj是 <__main__.Student object at 0x000001092EB60FA0> lu对象出生了return obj"""当new() return obj 时就调用init"""def __init__(self,name,score):       self.name=nameself.score=score"""对象(),调用 类的 call()"""def __call__(self, *args):# 这里的self就是对象lu,self和lu地址相同print(self)     # <__main__.Student object at 0x000001092EB60FA0>print(args)     # (1, 2, 3, 4, 5, 7, 9, 91)lu=Student("LuMinfei",120)
# 对象(),调用 类的 call()
lu(1,2,3,4,5,7,9,91)
print(lu)               # <__main__.Student object at 0x000001092EB60FA0>

type创建了类 ,type是元类

"""
简略写法
"""
class Person:pass
print(type(Person)) # <class 'type'>"""
实际上:
1.Person继承了object
2.type创建了Person
3. type就是传说中的元类,能创建各种 类
"""
class Person(object,metaclass=type):pass
print(type(Person)) # <class 'type'>

4.2 自定义元类 

元类(type) 生成 另一个元类,用 另一个元类 生成 常规的类(比如:Person, Student)

也可以说,改造一下type,用 改造过的type 创建常规类。用改造过的type的call方法来创建常规类

 定义HandsomeType,改造过的type

new()创建当前类对应的对象,HandsomeType对应的对象 是 Student类,

特别的

没有这种:handsometype=HandsomeType(),

只有 Student=HandsomeType(),

然后 lu=Student("name","score")

class HandsomeType(type):"""cls是HandsomeType类*args:是Student类的结构cls:<class '__main__.HandsomeType'>args:('Student', (), {'__module__': '__main__', '__qualname__': 'Student', '__new__': <function Student.__new__ at 0x000002785A349E50>, '__init__': <function Student.__init__ at 0x000002785A349EE0>})"""def __new__(cls,*args) :pass

完整的代码

# 英俊的Type也是继承于object,被type创建的
class HandsomeType(type):"""cls是HandsomeType类*args:是Student类的结构"""def __new__(cls,*args):"""可以替换成 obj=super().__new__(cls,*args)"""StudentClaxx=type.__new__(cls,*args)return StudentClaxx # return触发init()方法def __init__(self,*args):# 这里的self已经是Student类了print(self) # <class '__main__.Student'>pass"""当 lu = Student(lumingfei,120)时,call调用"""def __call__(self,*args):# self是Student类# Student类调用_new_()创建lu对象lu=self.__new__(self,*args)# 根据参数初始化lu对象self.__init__(lu,*args)return luclass Student(metaclass=HandsomeType):def __new__(cls,*args) :obj=object.__new__(cls)return objdef __init__(self,name,score) :self.name=nameself.score=score"""
此时,到这一样,Student类已经倍创建了
下一行的Student()会调用 HandsomeType的call方法()
"""
lu=Student("LuMingfei",135)
print(lu.name,lu.score)  # LuMingfei 135

这篇关于理解Python的元类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1062165

相关文章

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

Python使用Matplotlib绘制3D曲面图详解

《Python使用Matplotlib绘制3D曲面图详解》:本文主要介绍Python使用Matplotlib绘制3D曲面图,在Python中,使用Matplotlib库绘制3D曲面图可以通过mpl... 目录准备工作绘制简单的 3D 曲面图绘制 3D 曲面图添加线框和透明度控制图形视角Matplotlib

一文教你Python如何快速精准抓取网页数据

《一文教你Python如何快速精准抓取网页数据》这篇文章主要为大家详细介绍了如何利用Python实现快速精准抓取网页数据,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以了解下... 目录1. 准备工作2. 基础爬虫实现3. 高级功能扩展3.1 抓取文章详情3.2 保存数据到文件4. 完整示例

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

基于Python打造一个智能单词管理神器

《基于Python打造一个智能单词管理神器》这篇文章主要为大家详细介绍了如何使用Python打造一个智能单词管理神器,从查询到导出的一站式解决,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 项目概述:为什么需要这个工具2. 环境搭建与快速入门2.1 环境要求2.2 首次运行配置3. 核心功能使用指

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

利用Python打造一个Excel记账模板

《利用Python打造一个Excel记账模板》这篇文章主要为大家详细介绍了如何使用Python打造一个超实用的Excel记账模板,可以帮助大家高效管理财务,迈向财富自由之路,感兴趣的小伙伴快跟随小编一... 目录设置预算百分比超支标红预警记账模板功能介绍基础记账预算管理可视化分析摸鱼时间理财法碎片时间利用财

Python中的Walrus运算符分析示例详解

《Python中的Walrus运算符分析示例详解》Python中的Walrus运算符(:=)是Python3.8引入的一个新特性,允许在表达式中同时赋值和返回值,它的核心作用是减少重复计算,提升代码简... 目录1. 在循环中避免重复计算2. 在条件判断中同时赋值变量3. 在列表推导式或字典推导式中简化逻辑

python处理带有时区的日期和时间数据

《python处理带有时区的日期和时间数据》这篇文章主要为大家详细介绍了如何在Python中使用pytz库处理时区信息,包括获取当前UTC时间,转换为特定时区等,有需要的小伙伴可以参考一下... 目录时区基本信息python datetime使用timezonepandas处理时区数据知识延展时区基本信息