2014-02-12 42 views
0

我有一個類的屬性,讓說:最佳方式蟒蛇

#!/usr/bin/env python 

class testclass(object): 
    def __init__(self, a, b, c): 
     self.__attr1 = a 
     self.__attr2 = b 
     self.__attr3 = c 

    def meth(self): 
     ## run some checks on self.__attr1, self.__attr2, self.__attr3 
        ## How to do that? 

if __name__ == '__main__': 
    t = testclass("dd", "ee", "gg") 

問題: 萬一我有幾個屬性,而不是隻有三個是什麼寫meth方法的最佳途徑?我將對所有屬性運行相同的檢查。

回答

1

最簡單的方法是不要將它們存儲爲單個屬性。在這個例子中,我使用的說法包裝來傳遞ab,並c的元組abc,並存儲爲self._attrs

class testclass(object): 
    def __init__(self, *abc): 
     self._attrs = abc 

    def meth(self): 
     for attr in self._attrs: 
      print attr 

if __name__ == '__main__': 
    t = testclass("dd", "ee", "gg") 
+0

另外,如果你想訪問你的實例的所有屬性,你可以調用'dir(self)',但是你也會得到內建的。最好抓住你想要的東西,妥善保存 – mhlester

0

不是很肯定什麼ü上ATTR

意思檢查

但我仍然認爲

高清得到(個體經營,例如,所有者):

是somethi ng可以幫助你:)