0
我正在建立一個包含幾個列表以及其他變量的字典的類。我希望使用該類的人能夠將項目添加到列表中,但我想要通過setter方法,以便我可以確保它們添加到列表中的值是有效的。 getter方法更多的是爲用戶提供便利,因此不必爲了獲得值而鍵入variable.dictionary ['value'] ['subvalue'] ['third nested thing']。Python的getter和setter方法的列表和+ =運算符
我有一些可行的方法,但是在使用等號運算符時會調用setter方法。我想知道是否有可能在調用+ =時調用setter方法,因爲用戶將添加到列表中。這似乎更自然。
這裏是我做了什麼使一些僞遠
def addItemtoList(self,inValue):
if inValue in listOfAcceptableValues:
self.really['long']['nested']['dictionaries']['array'] = list(set(self.really['long']['nested']['dictionaries']['array'] + [inValue]))
def getDeeplyNestedList(self):
return self.really['long']['nested']['dictionaries']['array']
thatList = property(getDeeplyNestedList, addItemtoList)
對我而言,如果您創建了幾個簡單對象並使用了合成,那麼看起來像所有內容都會更容易和更易讀。 –
這很棘手,因爲'a + = b' *似乎*應該與'a = a + b'具有相同的行爲,但它實際上並沒有;它修改了列表,比如'a.extend(b)'。我不知道你是否可以在沒有繼承'list'的情況下解決這個問題。 – icktoofay
順便說一句,你可以讓字典一路下來,而不必使用'defaultdict'編寫自己的類:'''''''''''''''''' )' – icktoofay