理解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结合PyWebView库打造跨平台桌面应用

《Python结合PyWebView库打造跨平台桌面应用》随着Web技术的发展,将HTML/CSS/JavaScript与Python结合构建桌面应用成为可能,本文将系统讲解如何使用PyWebView... 目录一、技术原理与优势分析1.1 架构原理1.2 核心优势二、开发环境搭建2.1 安装依赖2.2 验

一文详解如何在Python中从字符串中提取部分内容

《一文详解如何在Python中从字符串中提取部分内容》:本文主要介绍如何在Python中从字符串中提取部分内容的相关资料,包括使用正则表达式、Pyparsing库、AST(抽象语法树)、字符串操作... 目录前言解决方案方法一:使用正则表达式方法二:使用 Pyparsing方法三:使用 AST方法四:使用字

Python列表去重的4种核心方法与实战指南详解

《Python列表去重的4种核心方法与实战指南详解》在Python开发中,处理列表数据时经常需要去除重复元素,本文将详细介绍4种最实用的列表去重方法,有需要的小伙伴可以根据自己的需要进行选择... 目录方法1:集合(set)去重法(最快速)方法2:顺序遍历法(保持顺序)方法3:副本删除法(原地修改)方法4:

Python运行中频繁出现Restart提示的解决办法

《Python运行中频繁出现Restart提示的解决办法》在编程的世界里,遇到各种奇怪的问题是家常便饭,但是,当你的Python程序在运行过程中频繁出现“Restart”提示时,这可能不仅仅是令人头疼... 目录问题描述代码示例无限循环递归调用内存泄漏解决方案1. 检查代码逻辑无限循环递归调用内存泄漏2.

Python中判断对象是否为空的方法

《Python中判断对象是否为空的方法》在Python开发中,判断对象是否为“空”是高频操作,但看似简单的需求却暗藏玄机,从None到空容器,从零值到自定义对象的“假值”状态,不同场景下的“空”需要精... 目录一、python中的“空”值体系二、精准判定方法对比三、常见误区解析四、进阶处理技巧五、性能优化

使用Python构建一个Hexo博客发布工具

《使用Python构建一个Hexo博客发布工具》虽然Hexo的命令行工具非常强大,但对于日常的博客撰写和发布过程,我总觉得缺少一个直观的图形界面来简化操作,下面我们就来看看如何使用Python构建一个... 目录引言Hexo博客系统简介设计需求技术选择代码实现主框架界面设计核心功能实现1. 发布文章2. 加

python logging模块详解及其日志定时清理方式

《pythonlogging模块详解及其日志定时清理方式》:本文主要介绍pythonlogging模块详解及其日志定时清理方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录python logging模块及日志定时清理1.创建logger对象2.logging.basicCo

Python如何自动生成环境依赖包requirements

《Python如何自动生成环境依赖包requirements》:本文主要介绍Python如何自动生成环境依赖包requirements问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录生成当前 python 环境 安装的所有依赖包1、命令2、常见问题只生成当前 项目 的所有依赖包1、

如何将Python彻底卸载的三种方法

《如何将Python彻底卸载的三种方法》通常我们在一些软件的使用上有碰壁,第一反应就是卸载重装,所以有小伙伴就问我Python怎么卸载才能彻底卸载干净,今天这篇文章,小编就来教大家如何彻底卸载Pyth... 目录软件卸载①方法:②方法:③方法:清理相关文件夹软件卸载①方法:首先,在安装python时,下

python uv包管理小结

《pythonuv包管理小结》uv是一个高性能的Python包管理工具,它不仅能够高效地处理包管理和依赖解析,还提供了对Python版本管理的支持,本文主要介绍了pythonuv包管理小结,具有一... 目录安装 uv使用 uv 管理 python 版本安装指定版本的 Python查看已安装的 Python