子类属性名称不同

时间:2013-04-23 15:04:54

标签: python

我希望子类的属性具有与其父类的相同属性不同的名称,即使它意味着相同的东西。例如,父类是具有属性“height”的Shape和具有类似arttribute“Diameter”的子类Circle。下面是我目前的简化,但我希望Circle类使用“直径”而不是“高度”。处理这个问题的最佳方法是什么?

注意:我将继承另一个类中的Circle,它也需要使用“diameter”而不是“height”。谢谢!

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.

1 个答案:

答案 0 :(得分:3)

您可以定义一个property来访问读写访问的原始属性:

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.

如果你经常想要这种行为并且你发现使用setter和getter的属性处理太不方便了,你可以更高一步build你自己的descriptor class

class AttrMap(object):
    def __init__(self, name):
        self.name = name
    def __get__(self, obj, typ):
        # Read access to obj's 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)

有了这个,你就可以做到

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

并且diameter描述符会将对它的所有访问重定向到命名属性(此处为:height)。