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

2023-11-25

我想创建一个使用与此类似的策略设计模式的类:

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(使用前将#替换为@)

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

随机推荐