list和+=op的python getter和setter方法

2024-09-30 02:33:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建一个类,它有一个字典,它包含几个列表和其他变量。我希望使用该类的人能够将项添加到列表中,但我希望使用setter方法,以便确保他们添加到列表中的值是有效的。getter方法更方便用户使用,因此不需要输入变量.dictionary['value']['subvalue']['third nested thing']只是为了得到一个值。在

我有一些有用的方法,但是当您使用equals运算符时会调用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)

Tags: 方法用户self列表字典defarraylong
1条回答
网友
1楼 · 发布于 2024-09-30 02:33:23

创建一个临时集仅仅用于一次性成员资格测试没有多大意义。不妨对list进行线性搜索

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

当有人试图用

^{pr2}$

对列表调用list.extend方法,因此addItemtoList根本不涉及。要实现您想要的,您需要thatList返回列表的包装版本。组合或子类化都可以

相关问题 更多 >

    热门问题