是否可以编写一个作用于类的方法并使用类的属性的装饰器?例如,我想向函数添加一个装饰器,如果类的某个属性(在用户调用函数时设置)为 False,该装饰器将返回错误。
例如,我的尝试(由于 is_active 无法访问 MyClass 的方法而导致代码损坏):
def is_active(active):
if active == False:
raise Exception("ERROR: Class is inactive")
class MyClass():
def __init__(self, active):
self.active = active
@is_active
def foo(self, variable):
print("foo")
return variable
@is_active
def bar(self, variable):
print("bar")
return variable
预期行为是:
cls = MyClass(active=True)
cls.foo(42)
---> function prints "foo" and returns 42
cls = MyClass(active=False)
cls.foo(42)
---> function raises an exception as the active flag is False
上面是一个虚拟示例,实际用例更复杂,但希望这能显示我面临的问题。
如果上述可行,我的额外问题是:是否可以根据此标志“隐藏”/删除实例化类中的方法。例如,如果用户使用 active=False
实例化该类然后当他们使用 iPython 并按 <tab>
时,他们只能看到允许使用的方法?
谢谢。
最佳答案
装饰器可能会令人困惑。请注意,函数作为参数传递,装饰器期望返回函数(或可调用对象)。所以你只需要返回一个不同的函数。由于 self
作为第一个参数传递给类方法,因此您拥有了所需的一切。您只需在装饰器中添加一个新函数来执行您想要的操作。
def is_active_method(func):
def new_func(*args, **kwargs):
self_arg = args[0] # First argument is the self
if not self_arg.active:
raise Exception("ERROR: Class is inactive")
return func(*args, **kwargs)
return new_func
class MyClass():
def __init__(self, active):
self.active = active
@is_active_method
def foo(self, variable):
print("foo")
return variable
@is_active_method
def bar(self, variable):
print("bar")
return variable
m = MyClass(True) # Prints foo from the method
m.foo(2)
m = MyClass(False) # Outputs the exception
m.foo(2)
关于python - 将装饰器应用于访问类属性的类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59956890/