加入收藏 | 设为首页 | 会员中心 | 我要投稿 济源站长网 (https://www.0391zz.cn/)- 数据工具、数据仓库、行业智能、CDN、运营!
当前位置: 首页 > 综合聚焦 > 编程要点 > 语言 > 正文

Python中元类是什么意思?怎么创建元类?

发布时间:2022-03-21 14:12:32 所属栏目:语言 来源:互联网
导读:Python中元类是什么?对于元类是Python学习中要掌握的内容,一些新手对于Python元类比较陌生,这篇文章就给大家简单介绍Python元类的概念和使用,接下来就跟随小编一起来学习吧。 1.python 中一切皆是对象,类本身也是一个对象,当使用关键字 class 的时候,
       Python中元类是什么?对于元类是Python学习中要掌握的内容,一些新手对于Python元类比较陌生,这篇文章就给大家简单介绍Python元类的概念和使用,接下来就跟随小编一起来学习吧。
 
       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>

(编辑:济源站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读