您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

5b51 2022/1/14 8:22:09 python 字数 4092 阅读 520 来源 www.jb51.cc/python

我想创建一个使用类似于此的策略设计模式的类: class C: @staticmethod def default_concrete_strategy(): print("default") @staticmethod def other_concrete_strategy(): print("other") def _

概述

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 = default_concrete_strategy替换策略= C.default_concrete_strategy将起作用,但认情况下,策略实例变量将是静态方法对象而不是可调用方法.

TypeError: 'staticmethod' object is not callable

如果我删除@staticmethod装饰器,它会工作,但还有其他方法吗?我希望自己记录认参数,以便其他人立即看到如何包含策略的示例.

此外,是否有更好的方法来公开策略而不是静态方法?我不认为实现完整的课程在这里有意义.

您可以直接使用函数对象:

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描述符本身不可调用).

另一种方法是使用哨兵认值;由于策略的所有正常值都是静态函数,因此没有一个可以正常工作:

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,因此调用描述符协议,并且在类定义完成之后,staticmethod描述符本身返回(未绑定)函数.

总结

以上是编程之家为你收集整理的python – 如何使用静态方法作为策略设计模式的默认参数?全部内容,希望文章能够帮你解决python – 如何使用静态方法作为策略设计模式的默认参数?所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶