2013-06-06 39 views
4

這個問題是風格之一。由於python中的屬性不是私有的,因此使用類似my_obj.attr之類的方法直接在類之外處理它們是否很好並且很常見?或者,也許,通過成員函數(如get_attr())這樣做是更好的做法,這是C++中的慣例?在python中尋址屬性的風格

+3

您不使用getter方法獲取Python中的簡單屬性! – schlamar

+0

通常情況下,您不需要獲取類屬性的getter,僅用於實例屬性。 – 0xc0de

+0

@ 0xc0de對不起。我的意思是對象的屬性。我已更正問題 – freude

回答

12

時聽起來像是你要使用的屬性:

class Foo(object): 
    def __init__(self, m): 
     self._m = m 
    @property 
    def m(self): 
     print 'accessed attribute' 
     return self._m 
    @m.setter 
    def m(self, m): 
     print 'setting attribute' 
     self._m = m 


>>> f = Foo(m=5) 
>>> f.m = 6 
setting attribute 
>>> f.m 
accessed attribute 
6 

這是訪問變量的最適應的方式,對於不需要執行此操作的簡單用例,在Python中,您可能會始終更改您r設計可以在以後免費使用屬性。

+0

我從來沒有聽說過這個。謝謝! – freude

+0

這個答案實際上讓我明白'@​​ property'裝飾者的作用。 +1 :) – TerryA

+3

「您可以隨時將設計更改爲免費使用屬性。」 - 重要的一點。 Python中的好設計是首先使用普通屬性,直到你發現你需要getters和setter。 _然後_你用一個屬性來替換它,並且客戶端代碼是不明智的。 –

2

創建類的實例,第一:

myinstance = MyClass() 
myinstance.attr 

否則你會得到這樣的錯誤AttributeError: class MyClass has no attribute 'attr'試圖做MyClass.attr