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

前端之家收集整理的这篇文章主要介绍了python – 如何使用静态方法作为策略设计模式的默认参数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想创建一个使用类似于此的策略设计模式的类:
  1. class C:
  2.  
  3. @staticmethod
  4. def default_concrete_strategy():
  5. print("default")
  6.  
  7. @staticmethod
  8. def other_concrete_strategy():
  9. print("other")
  10.  
  11. def __init__(self,strategy=C.default_concrete_strategy):
  12. self.strategy = strategy
  13.  
  14. def execute(self):
  15. self.strategy()

这给出了错误

  1. NameError: name 'C' is not defined

使用strategy = default_concrete_strategy替换策略= C.default_concrete_strategy将起作用,但默认情况下,策略实例变量将是静态方法对象而不是可调用方法.

  1. TypeError: 'staticmethod' object is not callable

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

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

解决方法

不,您不能,因为类定义尚未完成运行,因此当前名称空间中尚不存在类名.

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

  1. class C:
  2. @staticmethod
  3. def default_concrete_strategy():
  4. print("default")
  5.  
  6. @staticmethod
  7. def other_concrete_strategy():
  8. print("other")
  9.  
  10. def __init__(self,strategy=default_concrete_strategy.__func__):
  11. self.strategy = strategy

在定义方法时,C尚不存在,因此您可以通过本地名称引用default_concrete_strategy. .__ func__解包staticmethod描述符以访问底层原始函数(staticmethod描述符本身不可调用).

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

  1. class C:
  2. @staticmethod
  3. def default_concrete_strategy():
  4. print("default")
  5.  
  6. @staticmethod
  7. def other_concrete_strategy():
  8. print("other")
  9.  
  10. def __init__(self,strategy=None):
  11. if strategy is None:
  12. strategy = self.default_concrete_strategy
  13. self.strategy = strategy

由于这从self检索default_concrete_strategy,因此调用描述符协议,并且在类定义完成之后,staticmethod描述符本身返回(未绑定)函数.

猜你在找的Python相关文章