我想创建一个使用类似于此的策略设计模式的类:
class C:
@staticmethod
def default_concrete_strategy():
print("default")
@staticmethod
def other_concrete_strategy():
print("other")
def __init__(self, strategy=C.default_concrete_strategy):
self.strategy = strategy
def execute(self):
self.strategy()
这给出了错误:
NameError: name 'C' is not defined
替换strategy=C.default_concrete_strategy
为strategy=default_concrete_strategy
将起作用,但默认情况下,策略实例变量将是静态方法对象而不是可调用方法。
TypeError: 'staticmethod' object is not callable
如果我移除@staticmethod
装饰器,它会起作用,但还有其他方法吗?我希望默认参数是自我记录的,以便其他人可以立即看到如何包含策略的示例。
另外,有没有更好的方法来公开策略而不是静态方法?我认为在这里实施完整的课程没有意义。