Python:处理依赖于父类的继承类中的可变变量的类

时间:2015-11-30 16:20:43

标签: python inheritance

# -*- 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

实现以下结果的pythonic方法是什么:

  1. 当结果继承自Child2时 - 我希望getattr(Result, 'result_string')显示child2_replace child2_format

  2. 当结果从Child1继承时 - 我希望getattr(Result, 'result_string')显示child1_replace parent_format

  3. 问题是Result类应该是通用的 - 当这个类继承自Child1或Child2时,代码应该有用。如何在Python中实现这一点?

2 个答案:

答案 0 :(得分:0)

您可以使用properties来完成此操作。然后,您可以覆盖子类中的必要属性以获得所需的结果。例如:

class CommonParent(object):

    @property
    def format_field(self):
        return u'parent_format'

    @property
    def mutable_field(self):
        return u'parent_replace'

    @property
    def result_string(self):
        return '{0} {1}'.format(self.mutable_field, self.format_field)


class Child1(CommonParent):
    @property
    def mutable_field(self):
        return u'child1_replace'


class Child2(CommonParent):
    @property
    def format_field(self):
        return u'child2_format'

    @property
    def mutable_field(self):
        return u'child2_replace'


class Result1(Child1):
    pass


class Result2(Child2):
    pass


if __name__ == '__main__':
    r1 = Result1()
    print(getattr(r1, 'result_string'))

    r2 = Result2()
    print(getattr(r2, 'result_string'))

运行此脚本时,输出:

child1_replace parent_format
child2_replace child2_format

答案 1 :(得分:0)

我已经使用classmethod解决了它,不确定它是否正常,但它确实有效。

("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser.'&count=500'