<p>装饰器是一个接受函数或类并返回一个新函数或新类的高阶函数。它们通常通过 <code>@</code> 符号来使用
def class_decorator(cls):
class WrappedClass(cls):
def new_method(self):
print("This is a new method added by the decorator.")
def existing_method(self):
print("This method is overridden by the decorator.")
return WrappedClass
@class_decorator
class MyClass:
def existing_method(self):
print("This method exists in the original class.")
https://www.jb51.net/python...
在Python中,装饰器是一种允许我们在不改变原有代码的情况下,动态地增加或修改函数和类功能的工具。</p>
<p>类装饰器相较于函数装饰器,功能更为强大和灵活,因为它们不仅可以修饰类的方法,还可以修饰类本身。</p>
<p class="maodian"><a name="_label1"></a></p><h2>2. 装饰器的基本概念</h2>
<p>装饰器是一个接受函数或类并返回一个新函数或新类的高阶函数。它们通常通过 <code>@</code> 符号来使用
def class_decorator(cls):
class WrappedClass(cls):
def new_method(self):
print("This is a new method added by the decorator.")
def existing_method(self):
print("This method is overridden by the decorator.")
return WrappedClass
@class_decorator
class MyClass:
def existing_method(self):
print("This method exists in the original class.")
obj = MyClass()
obj.new_method() # 调用新增的方法
obj.existing_method() # 调用被重写的方法</pre></div>
<p>运行上述代码,输出结果为:</p>
<blockquote><p>This is a new method added by the decorator.<br />This method is overridden by the decorator.</p></blockquote>
<p>在这个例子中,<code>class_decorator</code> 是一个类装饰器,它接受一个类 <code>MyClass</code> 作为参数,并返回一个新的类 <code>WrappedClass</code>。<code>WrappedClass</code> 继承自 <code>MyClass</code>,并新增和重写了一些方法。</p>
<p class="maodian"><a name="_label2"></a></p><h2>3. 类装饰器的应用场景</h2>
<p>类装饰器在实际开发中有很多应用场景,下面是几个常见的例子:</p>
<p class="maodian"><a name="_lab2_2_2"></a></p><h3>3.1. 自动添加属性</h3>
<p>类装饰器可以用来自动为类添加一些属性。</p>
<p>例如,我们可以创建一个装饰器,自动为类添加一个 <code>created_at</code> 属性,记录对象的创建时间。</p>
<div class="jb51code"><pre class="brush:py;">import datetime
def add_timestamp(cls):
class WrappedClass(cls):
def init(self, args, **kwargs):
super().init(args, **kwargs)
self.created_at = datetime.datetime.now()
return WrappedClass
@add_timestamp
class MyClass:
def init(self, name):
self.name = name
obj = MyClass("Alice")
print(obj.name) # 输出: Alice
print(obj.created_at) # 输出: 对象的创建时间</pre></div>
<p class="maodian"><a name="_lab2_2_3"></a></p><h3>3.2 访问控制</h3>
<p>类装饰器可以用来控制类的方法访问权限。</p>
<p>例如,我们可以创建一个装饰器,要求调用某些方法时必须有管理员权限。</p>
<div class="jb51code"><pre class="brush:py;">def require_admin(cls):
class WrappedClass(cls):
def admin_method(self, args, **kwargs):
if not self.is_admin:
raise PermissionError("Admin privileges required")
return super().admin_method(args, **kwargs)
return WrappedClass
@require_admin
class MyClass:
def init(self, is_admin):
self.is_admin = is_admin
admin_obj = MyClass(is_admin=True)
admin_obj.admin_method() # 正常调用
user_obj = MyClass(is_admin=False)
user_obj.admin_method() # 抛出 PermissionError</pre></div>
<p class="maodian"><a name="_lab2_2_4"></a></p><h3>3.3 数据验证</h3>
<p>类装饰器可以用来在类方法调用前进行数据验证。</p>
<p>例如,我们可以创建一个装饰器,验证方法参数的类型。