2013-04-23 78 views
0

我想要一個子類的屬性具有不同於它的父類的相同屬性的名稱,即使它意味着同樣的事情。例如,父類是具有屬性「高度」的Shape和具有類似屬性「直徑」的子類Circle。下面簡單介紹一下我現在擁有的內容,但我希望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. 

回答

3

你可以定義一個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)。

+0

glglgl:非常感謝您的快速回復。如果我創建了一個繼承自Circle的孫子類,並且我還想使用「直徑」而不是「高度」,該怎麼辦?這是否意味着我必須重新做同樣的@property想法?謝謝! – JasonArg123 2013-04-23 15:28:18

+0

從第三個屬性中,您可以隨意訪問「直徑」和/或「高度」。對直徑的所有讀取訪問都被重定向到「高度」,以及所有的寫入訪問。 – glglgl 2013-04-23 15:33:46

+0

glglgl,這是非常好的。非常感謝! – JasonArg123 2013-04-23 17:19:13

相關問題