我想制作一个使用与此类似的策略设计模式的类:
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
装饰器它会起作用,但是还有其他方法吗?我希望对默认参数进行 self 记录,以便其他人可以立即看到有关如何包含策略的示例。
此外,是否有比静态方法更好的方法来公开策略?我认为在这里实现完整的类没有意义。
最佳答案
不,你不能,因为 class
定义还没有完成运行,所以类名在当前命名空间中还不存在。
您可以直接使用函数对象:
class C:
@staticmethod
def default_concrete_strategy():
print("default")
@staticmethod
def other_concrete_strategy():
print("other")
def __init__(self, strategy=default_concrete_strategy.__func__):
self.strategy = strategy
C
在定义方法时尚不存在,因此您通过本地名称引用 default_concrete_strategy
。 .__func__
解包 staticmethod
描述符以访问底层原始函数(staticmethod
描述符本身不可调用)。
另一种方法是使用哨兵默认值; None
在这里可以正常工作,因为 strategy
的所有正常值都是静态函数:
class C:
@staticmethod
def default_concrete_strategy():
print("default")
@staticmethod
def other_concrete_strategy():
print("other")
def __init__(self, strategy=None):
if strategy is None:
strategy = self.default_concrete_strategy
self.strategy = strategy
因为这从 self
中检索了 default_concrete_strategy
描述符协议(protocol)被调用并且(未绑定(bind)的)函数由 staticmethod
描述符本身返回,嗯在类定义完成之后。
关于python - 如何使用静态方法作为策略设计模式的默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21672041/