加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 22:57:14 所属栏目:Python 来源:网络整理
导读:我想创建一个使用类似于此的策略设计模式的类: 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
我想创建一个使用类似于此的策略设计模式的类:
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描述符本身返回(未绑定)函数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读