您可以定义一个在读写访问时访问原始属性的属性:
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
。