# -*- coding: utf-8 -*-
class CommonParent(object):
mutable_field = u'parent_replace'
format_field = u'parent_format'
full_pattern = u'{{to_replace}} {to_format}'
pattern = full_pattern.replace(u'{{to_replace}}', mutable_field)
result_string = pattern.format(
to_format=format_field
)
class Child1(CommonParent):
mutable_field = u'child1_replace'
class Child2(CommonParent):
mutable_field = u'child2_replace'
format_field = u'child2_format'
class Result(Child1):
pass
什麼是實現以下結果的Python的方式:的Python:類處理,其中依賴於父類繼承的類可變變量
當結果從CHILD2繼承 - 我想
getattr(Result, 'result_string')
顯示child2_replace child2_format
當結果從Child1繼承 - 我想
getattr(Result, 'result_string')
顯示child1_replace parent_format
問題是Result類應該是通用的 - 當這個類繼承自Child1或Child2時,代碼應該工作。如何在Python中實現這一點?