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

标签 python python-3.x static-methods strategy-pattern default-parameters

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

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/

相关文章:

python - 将每个键的值作为数组存储在字典中

c++ - 未定义的静态模板函数引用

python - Pandas 读取了分隔的 txt 文件的一部分

python - 查找包含 NaN 的行的索引

python - 如何使用 boto3 部署 AWS 无服务器应用程序模型模板?

json - 使用python在elasticsearch的json响应内搜索值

python - 在不包括当前行的两列之间创建一个带有 pandas groupby 划分的新列

python - python 中的 docopt 给我带来了问题

c++ - 在 C++ 中声明但未定义的静态函数

c++ - 在 C++ 中动态调用静态 "constructor"