如何使用静态方法作为策略设计模式的默认参数?


问题内容

我想创建一个使用类似于以下策略设计模式的类:

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_strategystrategy=default_concrete_strategy有效,但默认情况下,策略实例变量将是静态方法对象而不是可调用方法。

TypeError: 'staticmethod' object is not callable

如果删除@staticmethod装饰器,它将起作用,但是还有其他方法吗?我希望默认参数能够自我记录,以便其他人立即看到如何包含策略的示例。

另外,有没有比静态方法更好的方法来公开策略?我认为在这里实现完整的类没有意义。


问题答案:

不,您不能,因为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

由于这default_concrete_strategyself描述符协议中检索,因此调用了协议,staticmethod描述符本身返回了(未绑定)函数,因此很容易完成类定义。