使用另一个类的实例定义类变量

时间:2017-01-04 20:58:58

标签: python class inheritance

我已经设置了以下课程:

class External(object):

    def __init__(self, first, second):
        self.first = first
        self.second = second

    def foo():
        print('something')

class Parent(object):

    shirt_color = ''
    shoes_color = ''
    external_class = External(shirt_color, shoes_color)

class SouthParent(Parent):

    shirt_color = 'white'
    shoes_color = 'blue'

因为SouthParent是Parent的子级,并且在SouthParent类中重新定义了类变量shirt_color和shoes_color,所以External()将接收的预期参数应该是(' white',' blue& #39;)但它会收到('''')

这是以这种方式定义的,用于像SouthParent.external_class.foo()这样的终端,如Django Model(User.objects.all())

2 个答案:

答案 0 :(得分:0)

您永远不会在inbound--> type:PostgreSQL, protocol:TCP port range:5432, source:0.0.0.0/0 outbound--> type:All Traffic, protocol:All, port range:all, destination:0.0.0.0/0 上定义external_class,因此访问该属性会使用SouthParent中的external_class,其中Parent定义为External('', '')

如果您想根据类属性构建external_class,可以使用属性:

class Parent(object):

    shirt_color = ''
    shoes_color = ''

    @property
    def external_class(self):
        return External(self.shirt_color, self.shoes_color)

如果每次都应该是相同的 External实例,请这样做:

class Parent(object):

    shirt_color = ''
    shoes_color = ''

    _external_class = None

    @property
    def external_class(self):
        if self._external_class is None:
            self._external_class = External(self.shirt_color, self.shoes_color)
        return self._external_class

答案 1 :(得分:0)

可能的解决方案:(在@kindall的帮助下)

使用Python元类

class External(object):
    def __init__(self, first, second):
        self.first = first
        self.second = second

    def foo():
        print('something')

class ParentMeta(type):
    def __new__(cls, name, bases, attrs):

        if attrs['shirt_color'] and attrs['shoes_color']:
            attrs['external_class'] = External(attrs['odoo_model'],attrs['cache_name'])

        return super(ParentMeta, cls).__new__(cls, name, bases, attrs)

class Parent(metaclass=ParentMeta):

    shirt_color = ''
    shoes_color = ''         

class SouthParent(Parent):

    shirt_color = 'white'
    shoes_color = 'blue'


SouthParent.external_class.foo()
# something