如何在 class 中移动此方法装饰器模式?
How do I move this method-decorator pattern inside a class?
目前,我正在使用装饰器将 class 中的方法动态添加到列表中;这样我就可以在需要的时候同时遍历所有这些,而且我不需要一次手动添加它们中的每一个:
predicates_list = []
def predicate(func):
predicates_list.append(func)
return func
class Person(object):
@predicate
def name_is_bill(self, name):
return True if name == 'bill' else False
def test_everything(self, tester):
if any(predicate(name) for predicate in predicates_list:
return True
else:
return False
但是,在 Person class 范围之外使用装饰函数和列表是没有意义的——只有 Person class 或其子classes会使用它。我没有运气尝试使装饰器函数成为 class 方法或静态方法。
作为 class 方法,我得到关于需要两个参数的错误。 (这个错误是有道理的,但我是否需要将 cls
或 self
作为装饰器中的第一个参数传递?如果是,如何传递?)
作为静态方法,我无权访问 class 的属性。我可以在装饰器函数中指定 class 的名称,但如果我需要子 class 人,我会 运行 出问题。
一定有一种优雅的方法可以做到这一点,但我没有主意。
您使用的模式看起来是正确的。大部分例子在官方Python Decorator Library use the same pattern you've adopted - decorator definition outside the class. See, for instance, the Property Definition例子中。
目前,我正在使用装饰器将 class 中的方法动态添加到列表中;这样我就可以在需要的时候同时遍历所有这些,而且我不需要一次手动添加它们中的每一个:
predicates_list = []
def predicate(func):
predicates_list.append(func)
return func
class Person(object):
@predicate
def name_is_bill(self, name):
return True if name == 'bill' else False
def test_everything(self, tester):
if any(predicate(name) for predicate in predicates_list:
return True
else:
return False
但是,在 Person class 范围之外使用装饰函数和列表是没有意义的——只有 Person class 或其子classes会使用它。我没有运气尝试使装饰器函数成为 class 方法或静态方法。
作为 class 方法,我得到关于需要两个参数的错误。 (这个错误是有道理的,但我是否需要将 cls
或 self
作为装饰器中的第一个参数传递?如果是,如何传递?)
作为静态方法,我无权访问 class 的属性。我可以在装饰器函数中指定 class 的名称,但如果我需要子 class 人,我会 运行 出问题。
一定有一种优雅的方法可以做到这一点,但我没有主意。
您使用的模式看起来是正确的。大部分例子在官方Python Decorator Library use the same pattern you've adopted - decorator definition outside the class. See, for instance, the Property Definition例子中。