python - Override a field in parent class with property in child class -
where looks 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 none return value can compute a.y , b.a # if a.x not none return @x.setter def x(self, val): # set field value
sometimes want set assumed value x
hand, in case use a
. in other cases want use more complicated approach involves computing a.x
's value on basis of information organized b
. idea in code make c
class can a
(in terms of x
field) doesn't need field value set hand, instead gets derived.
what can't figure out how have c.x
property shadow a.x
field in sensible way.
the line self.x = val
in a.__init__
method invoke c.x
setter. have handled here. handling per instance attributes here, not attributes on class inherited subclasses.
all need set different attribute in setter represent x
value. name _x
, example:
class c(a, b): _x = none @property def x(self): if self._x not none: return self._x return self.a + self.y @x.setter def x(self, val): self._x = val
note if c.__init__
call super().__init__
, don't need @ all. however, do need make sure @ least a.__init__()
plays along in inheritance structure; add in more calls super().__init__()
:
class a(object): def __init__(self, val, *args, **kwargs): super(a, self).__init__(*args, **kwargs) self.x = val self.y = 42 class b(object): def __init__(self, *args, **kwargs): super(b, self).__init__(*args, **kwargs) self.a = 22
using *args
, **kwargs
allows these methods pass on arguments other classes in hierarchy.
demo, using above classes:
>>> c = c(none) >>> c.x 64 >>> c.x = 15 >>> c.x 15
Comments
Post a Comment