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>
到此這篇關于Python基礎之元類詳解的文章就介紹到這了,更多相關Python元類詳解內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- Python自定義元類的實例講解
- 詳解python metaclass(元類)
- 一篇文章帶你了解python迭代器和生成器
- 正確理解python迭代器與生成器
- python學習之可迭代對象、迭代器、生成器
- Python元類與迭代器生成器案例詳解