Child class attribute

I want the attribute of the child class to have a different name than the same attribute of its parent class, although this means the same thing. For example, the parent class is a Shape with the "height" attribute and a Circle child with the same arttribute "Diameter" attribute. The following is a simplification of what I have, but I want the Circle class to use "diameter" instead of "height". What is the best way to handle this?

NOTE. I will inherit from Circle in another class, which should also use "diameter" instead of "height". Thanks!

class Shape(): def __init__(self, shape, bar_args, height): self.shape = shape self.height = height etc. class Circle(Shape): def __init__(self, height, foo_args, shape='circle'): Shape.__init__(self, shape, height) self.height = height etc. 
0
source share
1 answer

You can define a property that accesses the original attribute for read and write access:

 class Circle(Shape): def __init__(self, height, foo_args, shape='circle'): Shape.__init__(self, shape, height) # assigns the attributes there # other assignments @property def diameter(self): """The diameter property maps everything to the height attribute.""" return self.height @diameter.setter def diameter(self, new_value): self.height = new_value # deleter is not needed, as we don't want to delete this. 

If you want this behavior to be very common, and you find that handling properties with setter and getter is too unmanageable, you can take the step above and build your own descriptor class :

 class AttrMap(object): def __init__(self, name): self.name = name def __get__(self, obj, typ): # Read access to obj attribute. if obj is None: # access to class -> return descriptor object. return self return getattr(obj, self.name) def __set__(self, obj, value): return setattr(obj, self.name, value) def __delete__(self, obj): return delattr(obj, self.name) 

With this you can do

 class Circle(Shape): diameter = AttrMap('height') def __init__(self, height, foo_args, shape='circle'): Shape.__init__(self, shape, height) # assigns the attributes there # other assignments 

and the diameter descriptor redirects all calls to it by the specified attribute (here: height ).

+3
source

All Articles