欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python基礎(chǔ)之元類詳解

 更新時間:2021年04月29日 16:04:43   作者:思想流浪者  
這篇文章主要介紹了Python基礎(chǔ)之元類詳解,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)python基礎(chǔ)的小伙伴們有非常好的幫助,需要的朋友可以參考下

1.python 中一切皆是對象,類本身也是一個對象,當(dāng)使用關(guān)鍵字 class 的時候,python 解釋器在加載 class 的時候會創(chuàng)建一個對象(這里的對象指的是類而非類的實例)

class Student:
    pass
 
s = Student()
print(type(s))  # <class '__main__.Student'>
print(type(Student))  # <class 'type'>

2.什么是元類

元類是類的類,是類的模板
元類是用來控制如何創(chuàng)建類的,正如類是創(chuàng)建對象的模板一樣
元類的實例為類,正如類的實例為對象。
type 是python 的一個內(nèi)建元類,用來直接控制生成類,python中任何 class 定義的類其實是 type 類實例化的對象

3.創(chuàng)建類的兩種方法:

# 方法一
class Student:
    def info(self):
        print("---> student info")
 
# 方法二
def info(self):
    print("---> student info")
 
Student = type("Student", (object,), {"info": info, "x": 1})

4.一個類沒有聲明自己的元類,默認(rèn)其元類是 type, 除了使用元類 type, 用戶也可以通過繼承 type 來自定義元類

class Mytype(type):
    def __init__(self, a, b, c):
        print("===》 執(zhí)行元類構(gòu)造方法")
        print("===》 元類__init__ 第一個參數(shù):{}".format(self))
        print("===》 元類__init__ 第二個參數(shù):{}".format(a))
        print("===》 元類__init__ 第三個參數(shù):{}".format(b))
        print("===》 元類__init__ 第四個參數(shù):{}".format(c))
 
    def __call__(self, *args, **kwargs):
        print("=====》 執(zhí)行元類__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))
 
# 結(jié)果:
#     ===》 執(zhí)行元類構(gòu)造方法
#     ===》 元類__init__ 第一個參數(shù):<class '__main__.Student'>
#     ===》 元類__init__ 第二個參數(shù):Student
#     ===》 元類__init__ 第三個參數(shù):()
#     ===》 元類__init__ 第四個參數(shù):{'__module__': '__main__', '__qualname__': 'Student', '__init__': <function Student.__init__ at 0x00000269BCA9A670>}
#     Student類:<class '__main__.Student'>
#     =====》 執(zhí)行元類__call__方法
#     =====》 元類__call__ args:('xu',)
#     =====》 元類__call__ kwargs:{}
#     實例:<__main__.Student object at 0x00000269BC9E8400>

到此這篇關(guān)于Python基礎(chǔ)之元類詳解的文章就介紹到這了,更多相關(guān)Python元類詳解內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論