我想创建一个使用与此类似的策略设计模式的类:
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
with strategy=default_concrete_strategy
可以工作,但如果保留默认值,策略实例变量将是静态方法对象而不是可调用方法。
TypeError: 'staticmethod' object is not callable
如果我删除它就会起作用@staticmethod
装饰器,但是还有其他方法吗?我希望默认参数能够自我记录,以便其他人立即看到如何包含策略的示例。
另外,是否有比静态方法更好的方式来公开策略?我认为在这里实施完整的课程没有意义。
不,你不能,因为class
定义尚未完成运行,因此当前命名空间中尚不存在类名。
You can直接使用函数对象:
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
用于访问底层原始函数的描述符(astaticmethod
描述符本身不可调用)。
另一种方法是使用哨兵默认值;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
由于这检索default_concrete_strategy
from self
调用描述符协议并返回(未绑定)函数staticmethod
描述符本身,在类定义完成之后。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)