最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

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

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

2.什么是元類

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

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.一個(gè)類沒有聲明自己的元類,默認(rèn)其元類是 type, 除了使用元類 type, 用戶也可以通過繼承 type 來自定義元類

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

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

相關(guān)文章

最新評(píng)論

馆陶县| 盐池县| 新民市| 德阳市| 老河口市| 阆中市| 白水县| 获嘉县| 玉溪市| 商丘市| 大足县| 河间市| 册亨县| 招远市| 镇宁| 双流县| 安吉县| 合山市| 定襄县| 遂宁市| 正宁县| 东丰县| 隆回县| 芮城县| 惠安县| 怀集县| 绥化市| 盖州市| 铁岭市| 霍邱县| 金坛市| 鹤峰县| 东莞市| 梁平县| 布尔津县| 东至县| 新昌县| 桦南县| 左云县| 城市| 加查县|