[Tutor] calling setters of superclasses
Gregory, Matthew
matt.gregory at oregonstate.edu
Sat Dec 18 01:48:30 CET 2010
Hi all,
Consider the following classes where PositiveX should constrain the attribute _x to be positive and SmallX should further constrain the attribute _x to be less than 10.
class PositiveX(object):
def __init__(self):
self._x = 1
@property
def x(self):
return self._x
@x.setter
def x(self, val):
if val < 0:
raise ValueError('Negatives not allowed')
self._x = val
class SmallX(PositiveX):
@property
def x(self):
return self._x
@x.setter
def x(self, val):
# How do I call the superclass' @x.setter
super(SmallX, self).__setattr__('x', val)
if val > 10:
raise ValueError('Big values not allowed')
self._x = val
I thought I could call the superclass setter first to ensure the value was positive, but I'm getting an infinite recursion. I also tried:
super(SmallX, self).x = val
but I get this:
AttributeError: 'super' object has no attribute 'x'
I'm fully confused and, therefore, likely doing something stupid.
thanks, matt
More information about the Tutor
mailing list