有条件地用另一个类方法修饰类方法

2024-06-13 16:57:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

背景

使用python2.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是作为字符串转储到文本文件中的字典。dictionary对象因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

问题

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

也许是其他层次的装饰师或者更好的Python方式


Tags: and方法selfreportdictionaryreturnobjectdef
1条回答
网友
1楼 · 发布于 2024-06-13 16:57:55

就用继承吧

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

相关问题 更多 >