简体   繁体   中英

python getter and setter methods for list and += operator

I am building a class which has a dictionary that contains several lists along with other variables. I would like for people using the class to be able to add items to the lists, but I want to go through a setter method so that I can ensure that the values they add to the list are valid. The getter method serves more as a convenience for the user so that it wont be necessary to type variable.dictionary['value']['subvalue']['third nested thing'] just to get at a value.

I have something that works, but the setter method is called when you use the equals operator. I was wondering if it is possible to call the setter method when += is called since the user will be adding to a list. That just seems more natural.

Here is some pseudocode of what I've done so far

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)

There's not much point creating a temporary set just to use it for a one off membership test. Might as well just to a linear search of the list

def addItemtoList(self,inValue):
    L = self.really['long']['nested']['dictionaries']['array']
    if inValue in listOfAcceptableValues and inValue not in L:
        L.append(inValue)

When someone tries to extend the list using

foo.thatList += ['Some', 'items']

the list.extend method is called on the list, so the addItemtoList isn't involved at all. To achieve what you want, you'll need to have thatList return a wrapped version of the list. Either composition or subclassing will work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM