子类属性不同

2024-04-16 08:22:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望子类的属性与父类的同一属性具有不同的名称,即使它的含义相同。例如,父类是属性为“height”的Shape,子类是属性为“Diameter”的Circle。下面是对我当前拥有的内容的简化,但是我希望Circle类使用“diameter”而不是“height”。处理这个问题最好的方法是什么?你知道吗

注意:我将继承另一个类中的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.

Tags: self名称属性initdefetcargs子类
1条回答
网友
1楼 · 发布于 2024-04-16 08:22:01

您可以定义一个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)。你知道吗

相关问题 更多 >