我认为这是另一个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对象因Report
和Legacy_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方式
就用继承吧
相关问题 更多 >
编程相关推荐