Python 中的元类
本教程将讨论 Python 中面向对象上下文中的元类。
Python 中的元类
简单地说,元类定义了类的行为。常规类定义对象或类的实例的行为方式。
在 Python 中,元类是预制的和隐式的;这意味着在创建类时在后台创建了一个元类。
Python 中的 object 基类
在 Python 中,隐式创建的每个类都继承了基类 object。在 object 类中有内置的私有方法,如 __init__ 和 __new__。在一个类甚至开始创建自己的字段、函数和属性之前,它们都会继承 object 类中的任何属性。
例如,让我们创建一个新类 ChildObject。在这个类中是单个属性和单个函数的声明。
class ChildObject:
num = 1
def printStatement():
print("This is a child object.")
要验证 ChildObject 类是否继承了 object 类中的任何属性和函数,请使用 dir() 函数,该函数返回在指定对象中定义的所有函数和属性的列表。
print(dir(ChildObject))
输出:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'num', 'printStatement']
观察到在 num 属性和 printStatement 函数之前,有相当多的私有属性和函数没有在 ChildObject 中明确定义;这意味着它们要么在类中隐式定义,要么从 object 类继承。
让我们使用相同的函数 dir() 检查 object 类的属性和函数:
print(dir(object))
输出:
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
Python 中的 type 元类
现在我们已经讨论了 object 类,让我们讨论 Python 中的实际元类,type。同样,元类是一个实例化并定义另一个类的行为的类。
两个函数可以公开给定类的元类:type() 和 __class__。这两个函数都输出给定参数的类。
例如,让我们对上述示例中的给定 ChildObject 类使用 type() 和 __class__ 函数。
class ChildObject:
num = 1
def printStatement():
print("This is a child object.")
print(type(ChildObject))
print(ChildObject.__class__)
输出:
<class 'type'>
<class 'type'>
两个函数都输出 <class 'type'>。这表明 ChildObject 类属于 type 类型。type 是 ChildObject 类和任何其他类的元类。
总之,type 是隐式定义任何实例化类行为的元类。这不被视为常识,因为这是在代码后台完成的,没有开发人员的干预。所以元类的概念只有在有人深入研究 Python 源代码和文档时才知道。
Skilled in Python, Java, Spring Boot, AngularJS, and Agile Methodologies. Strong engineering professional with a passion for development and always seeking opportunities for personal and career growth. A Technical Writer writing about comprehensive how-to articles, environment set-ups, and technical walkthroughs. Specializes in writing Python, Java, Spring, and SQL articles.
LinkedIn