0

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

注意:我将在另一个类中从 Circle 继承,该类也需要使用“直径”而不是“高度”。谢谢!

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.
4

1 回答 1

3

您可以定义一个在读写访问时访问原始属性的属性

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 处理属性太不方便,您可以更进一步并构建自己的描述符类

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

于 2013-04-23T15:18:36.770 回答