如何使用静态方法作为策略设计模式的默认参数? [英] How can I use a static method as a default parameter for the strategy design pattern?
问题描述
我想创建一个使用类似于以下策略设计模式的类:
I want to make a class that uses a strategy design pattern similar to this:
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
即可,但是默认情况下,策略实例变量将是静态方法对象而不是可调用方法。
Replacing strategy=C.default_concrete_strategy
with strategy=default_concrete_strategy
will work but, left as default, the strategy instance variable will be a static method object rather than a callable method.
TypeError: 'staticmethod' object is not callable
如果删除 @staticmethod,它将起作用
装饰器,但是还有其他方法吗?我希望默认参数可以自我记录,以便其他人可以立即看到如何包含策略的示例。
It will work if I remove the @staticmethod
decorator, but is there some other way? I want the default parameter to be self documented so that others will immediately see an example of how to include a strategy.
此外,有没有更好的方法来公开策略而不是而不是静态方法?我认为在这里实现完整的类没有意义。
Also, is there a better way to expose strategies rather than as static methods? I don't think that implementing full classes makes sense here.
推荐答案
不,您不能,因为 class
定义尚未完成运行,因此该类名称在当前名称空间中尚不存在。
No, you cannot, because the class
definition has not yet completed running so the class name doesn't exist yet in the current namespace.
您可以直接使用函数对象:
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
描述符本身不是可调用的。)
C
doesn't exist yet when the methods are being defined, so you refer to default_concrete_strategy
by the local name. .__func__
unwraps the staticmethod
descriptor to access the underlying original function (a staticmethod
descriptor is not itself callable).
另一种方法是使用前哨默认值。 None
在这里可以正常工作,因为 strategy
的所有正常值都是静态函数:
Another approach would be to use a sentinel default; None
would work fine here since all normal values for strategy
are static functions:
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
来自 self
调用描述符协议,并且($ un $)函数由 static方法返回
描述符本身,在类定义完成之后。
Since this retrieves default_concrete_strategy
from self
the descriptor protocol is invoked and the (unbound) function is returned by the staticmethod
descriptor itself, well after the class definition has completed.
这篇关于如何使用静态方法作为策略设计模式的默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!