Python 简明教程
Python - Metaclasses
Metaclasses 是 Python 中的一项强大功能,允许您自定义类创建。通过使用元类,您可以向类中添加特定的行为、属性和方法,从而允许您创建更灵活、更有效的程序。此类提供了使用 metaprogramming 在 Python 中工作的能力。
Metaclasses are a powerful feature in Python that allow you to customize class creation. By using metaclasses, you can add specific behaviors, attributes, and methods to classes, and allowing you to create more flexible, efficient programs. This classes provides the ability to work with metaprogramming in Python.
Metaclasses 是 OOP concept 默认情况下存在于所有 Python 代码中。Python 通过使用关键字 type 提供创建自定义元类的功能。Type 是一种元类,其实例是类。在 Python 中创建的任何类都是 type 元类的实例。
Metaclasses are an OOP concept present in all python code by default. Python provides the functionality to create custom metaclasses by using the keyword type. Type is a metaclass whose instances are classes. Any class created in python is an instance of type metaclass.
Creating Metaclasses in Python
元类是一种类的类,它定义了类的行为方式。Python 中的每个类都是其元类的实例。默认情况下,Python 使用 type() function 构造元类。但是,您可以定义自己的元类来自定义类创建和行为。
A metaclass is a class of a class that defines how a class behaves. Every class in Python is an instance of its metaclass. By default, Python uses type() function to construct the metaclasses. However, you can define your own metaclass to customize class creation and behavior.
在定义类时,如果没有明确指定基类或元类,则 Python 使用 type() 来构建类。然后在新的命名空间中执行其主体,生成的类名称局部链接到 type(name, bases, namespace) 的输出。
When defining a class, if no base classes or metaclass are explicitly specified, then Python uses type() to construct the class. Then its body is executed in a new namespace, resulting class name is locally linked to the output of type(name, bases, namespace).
Example
让我们观察在不指定特定基类或元类的情况下创建类对象的结果
Let’s observe the result of creating a class object without specifying specific bases or a metaclass
class Demo:
pass
obj = Demo()
print(obj)
Output
通过执行以上的程序,你会得到以下结果:
On executing the above program, you will get the following results −
<__main__.Demo object at 0x7fe78f43fe80>
此示例演示了如何利用元类在 Python 中进行元编程的基础知识。以上输出表明 obj 是 Demo 类的实例,位于内存位置 0x7fe78f43fe80 。这是 Python 元类的默认行为,允许我们轻松地检查类的详细信息。
This example demonstrates the basics of metaprogramming in Python using metaclasses. The above output indicates that obj is an instance of the Demo class, residing in memory location 0x7fe78f43fe80. This is the default behavior of the Python metaclass, allowing us to easily inspect the details of the class.
Creating Metaclasses Dynamically
Python 中的 type() 函数可以用于动态创建类元类。
The type() function in Python can be used to create classes metaclasses dynamically.
Example
在此示例中,DemoClass 将使用 type() 函数创建,该类的实例也将被创建并显示。
In this example, DemoClass will created using type() function, and an instance of this class is also created and displayed.
# Creating a class dynamically using type()
DemoClass = type('DemoClass', (), {})
obj = DemoClass()
print(obj)
Output
执行上述程序后,您将获得以下结果:
Upon executing the above program, you will get the following results −
<__main__.DemoClass object at 0x7f9ff6af3ee0>
Example
这里提供另一个 creating a Metaclass with inheritance 的范例,可以通过使用 type() 函数从另一个类来继承。
Here is another example of creating a Metaclass with inheritance which can be done by inheriting one from another class using type() function.
class Demo:
pass
Demo2 = type('Demo2', (Demo,), dict(attribute=10))
obj = Demo2()
print(obj.attribute)
print(obj.__class__)
print(obj.__class__.__bases__)
Output
输出如下:
Following is the output −
10
<class '__main__.Demo2'>
(<class '__main__.Demo'>,)
Customizing Metaclass Creation
在 Python 中,您可以通过定义您自己的元类来定制类的创建和初始化。这一定制对于各种元编程任务非常有用,例如向类的所有实例中添加特定行为或在多个类中强制执行特定模式。
In Python, you can customize how classes are created and initialized by defining your own metaclass. This customization is useful for various metaprogramming tasks, such as adding specific behavior to all instances of a class or enforcing certain patterns across multiple classes.
可以通过重写元类中的方法来定制类,特别是 new 和 init 。
Customizing the classes can be done by overriding methods in the metaclass, specifically new and init.
Example
我们来看一个范例,演示我们在 Python 中使用元类的 new 方法定制类创建。
Let’s see the example of demonstrating how we can customize class creation using the new method of a metaclass in python.
# Define a custom metaclass
class MyMetaClass(type):
def __new__(cls, name, bases, dct):
dct['version'] = 1.0
# Modify the class name
name = 'Custom' + name
return super().__new__(cls, name, bases, dct)
# MetaClass acts as a template for the custom metaclass
class Demo(metaclass=MyMetaClass):
pass
# Instantiate the class
obj = Demo()
# Print the class name and version attribute
print("Class Name:", type(obj).__name__)
print("Version:", obj.version)
Output
执行上述代码后,你将获得以下结果 −
While executing above code, you will get the following results −
Class Name: CustomDemo
Version: 1.0
Example
这里提供另一个范例,演示如何在 Python 中使用 init 定制元类。
Here is another example that demonstrates how to customize the metaclass using the init in Python.
# Define a custom metaclass
class 2yCreating MetaClass(type):
def __init__(cls, name, bases, dct):
print('Initializing class', name)
# Add a class-level attribute
cls.version= 10
super().__init__(name, bases, dct)
# Define a class using the custom metaclass
class MyClass(metaclass=MyMetaClass):
def __init__(self, value):
self.value = value
def display(self):
print(f"Value: {self.value}, Version: {self.__class__.version}")
# Instantiate the class and demonstrate its usage
obj = MyClass(42)
obj.display()
Output
执行上述代码后,你将获得以下结果 −
While executing above code, you will get the following results −
Initializing class MyClass
Value: 42, Version: 10