Python 简明教程
Python - Wrapper Classes
在 Python 中, function 是一个一阶对象。一个函数可以将另一个函数作为其参数,并在其内部包装另一个函数定义。这有助于修改一个函数,而不实际改变它。这样的函数叫做 decorators 。
A function in Python is a first-order object. A function can have another function as its argument and wrap another function definition inside it. This helps in modifying a function without actually changing it. Such functions are called decorators.
此特性也适用于 wrapping a class 。此技术用于在类实例化之后通过对其逻辑进行 Wrapped 包装来管理此类。
This feature is also available for wrapping a class. This technique is used to manage the class after it is instantiated by wrapping its logic inside a decorator.
Example
def decorator_function(Wrapped):
class Wrapper:
def __init__(self,x):
self.wrap = Wrapped(x)
def print_name(self):
return self.wrap.name
return Wrapper
@decorator_function
class Wrapped:
def __init__(self,x):
self.name = x
obj = Wrapped('TutorialsPoint')
print(obj.print_name())
此处, Wrapped 是要包装的类的名称。它作为参数传递给一个函数。在函数内部,我们有一个 Wrapper class ,通过传递类 attributes 修改其行为,并返回修改后的类。返回的类被实例化,现在可以调用它的 method 。
Here, Wrapped is the name of the class to be wrapped. It is passed as argument to a function. Inside the function, we have a Wrapper class, modify its behavior with the attributes of the passed class, and return the modified class. The returned class is instantiated and its method can now be called.
执行此代码时,它将生成以下 output -
When you execute this code, it will produce the following output −
TutorialsPoint