読み取りおよび書き込みアクセスで元の属性にアクセスするプロパティを定義できます。
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
) にリダイレクトします。