dimanche 12 juin 2016

Override a field in parent class with property in child class


Where I am now looks like this:

class A(object):
    def __init__(self, val):
        self.x=val
        self.y=42
        # other fields

class B(object):
    def __init__(self):
        self.a=22
        # other fields

class C(A,B):
    def __init__(self, val):
        super(C,self).__init__(val)
    @property
    def x(self):
        # if A.x is None return a value that I can compute from A.y and B.a
        # if A.x is not None return it
    @x.setter
    def x(self, val):
        # set the field value

Sometimes I just want to set an assumed value for x by hand, in which case I would just use an A. In other cases I want to use a more complicated approach that involves computing A.x's value on the basis of information that is organized into a B. The idea in this code is to make a C class that can look like an A (in terms of the x field) but doesn't need that field value to be set by hand, instead it just gets derived.

What I can't figure out is how to have the C.x property shadow the A.x field in a sensible way.


Aucun commentaire:

Enregistrer un commentaire