0

同じことを意味していても、子クラスの属性に親クラスの同じ属性とは異なる名前を付けたいです。たとえば、親クラスは属性「height」を持つ Shape であり、子クラス Circle は同様の属性「Diameter」を持つとします。以下は私が現在持っているものを簡略化したものですが、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 に答える