【问题标题】:Decorate class method with another class method, conditionally有条件地用另一个类方法装饰类方法
【发布时间】:2019-11-02 14:37:45
【问题描述】:

我认为这是对另一个 question 的扩展

背景

使用 python 2.7,我有一个类

class Report(object):
  def translate_report(self, report_entity):
    ... # Process report_entity dictionary and return results

# But there is a legacy report class too
class Legacy_Report(object):
  def translate_report(self, legacy_report_entity):
    ... # Process report_entity dictionary in different way and return results

report_entity 是在文本文件中作为字符串转储的字典。字典对象因ReportLegacy_Report 而异。

要求

我将使用此字典重新创建对象实例并调用translate_report。无论实体是旧版本还是新版本,调用方法都是不可知的。

我的方法

class Legacy_Report(object):
  @staticmethod
  def _legacy_translation(legacy_report_entry):
    ... # Process
    return legacy_report_entry

  def __call__(self, underlying_function):
    def wrapper_func(self, report_object):
      if 'legacy' in report_object.keys():
        return Decorator._legacy_translation(report_object)
      else:
        return underlying_function(self, report_object)
    return wrapper_func

class Report(object):
  @Legacy_Report()
  def translate_report(self, report_entity):
    ... # Process report_entity 
    return report_entity

问题

虽然这可行,但这是实现这一目标的正确方法吗?

也许是其他级别的装饰器或更好的pythonic方式?

【问题讨论】:

    标签: python python-2.7 python-decorators


    【解决方案1】:

    只使用继承。

    class Report(object):
        def translate_report(self, report_entity):
            ... # Process report_entity dictionary and return results
    
    
    class Legacy_Report(Report):
        def translate_report(self, legacy_report_entity):
            ... # Process the legacy report differently
    

    【讨论】:

    • 那会破坏目的。根据 OOPS 范式,它们不应该继承,因为它们是不相关的。另外,translate_report 的调用应该基于report_entity 的内容
    • 我假设该类包含 除了 translate_report 方法的东西;否则,首先上课的意义是什么?
    • 有点。遗留报表类基本上只是__dict__ 的扩展,几乎没有其他方法。不过,较新的报告类真的很漂亮:)
    • 任何pythonic解决方案,任何人??
    猜你喜欢
    • 2021-10-23
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 2018-08-15
    • 1970-01-01
    • 2014-01-14
    • 2011-07-03
    相关资源
    最近更新 更多