Child Class Attribute Different Name
I want an attribute of a child class to have a different name than the same attribute of its parent class even though it means the same thing. For example, a parent class is Shape
Solution 1:
You could define a property which accesses the original attribute on read and write access:
classCircle(Shape):
def__init__(self, height, foo_args, shape='circle'):
Shape.__init__(self, shape, height) # assigns the attributes there# other assignments @propertydefdiameter(self):
"""The diameter property maps everything to the height attribute."""return self.height
@diameter.setterdefdiameter(self, new_value):
self.height = new_value
# deleter is not needed, as we don't want to delete this.If you want this behaviour very often and you find property handling with setter and getter too unhandy, you can go a step higher and build your own descriptor class:
classAttrMap(object):
def__init__(self, name):
self.name = name
def__get__(self, obj, typ):
# Read access to obj's attribute.if obj isNone:
# access to class -> return descriptor object.return self
returngetattr(obj, self.name)
def__set__(self, obj, value):
returnsetattr(obj, self.name, value)
def__delete__(self, obj):
returndelattr(obj, self.name)
With this, you can then do
classCircle(Shape):
diameter = AttrMap('height')
def__init__(self, height, foo_args, shape='circle'):
Shape.__init__(self, shape, height) # assigns the attributes there# other assignmentsand the diameter descriptor will redirect all accesses to it to the named attribute (here: height).
Post a Comment for "Child Class Attribute Different Name"