你可以定義一個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.
如果你想這種行爲非常頻繁,你找物業與二傳手處理和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
)。
glglgl:非常感謝您的快速回復。如果我創建了一個繼承自Circle的孫子類,並且我還想使用「直徑」而不是「高度」,該怎麼辦?這是否意味着我必須重新做同樣的@property想法?謝謝! – JasonArg123 2013-04-23 15:28:18
從第三個屬性中,您可以隨意訪問「直徑」和/或「高度」。對直徑的所有讀取訪問都被重定向到「高度」,以及所有的寫入訪問。 – glglgl 2013-04-23 15:33:46
glglgl,這是非常好的。非常感謝! – JasonArg123 2013-04-23 17:19:13