使用属性从列表中追加和删除元素

时间:2016-10-06 09:09:33

标签: python python-3.x

在我的基类中, _mylist 定义为列表

class Foo(object):

    def __init__(self):
        self._mylist = list()

    @property
    def mylist(self):
        return self._mylist

    @mylist.setter
    def mylist(self, value):
        self._mylist = value

在我的派生类Boo

class Boo(Foo)
    def __init__(self):
    """   """

    def add_element(self,value):
        Foo.mylist.appened(value)

我想从 Boo 添加和删除 mylist 的元素。 我尝试了以下方法:

boo = Boo()
boo.add\_element(5)

出现以下异常:

AttributeError: 'property' object has no attribute 'append'

目前我将 mylist 的setter属性修改为:

    @mylist.setter
    def mylist(self, value):
        self._mylist.append( value )

这允许我向 mylist 添加元素,但我不知道如何从中删除元素。

是否有更好的方法可以从派生类中修改基类中的列表?

2 个答案:

答案 0 :(得分:1)

为什么必须改变setter的语义?

如果只是使用list的方法操作列表会怎样。

class Foo(object):

    def __init__(self):
        self._mylist = list()

    @property
    def mylist(self):
        return self._mylist

    @mylist.setter
    def mylist(self, value):
        self._mylist = value

class Boo(Foo):
    pass

b = Boo()
b.mylist.append(1)  # append directly
b.mylist.append(2)
b.mylist.append(3)
b.mylist.remove(2)  # remove directly

答案 1 :(得分:-2)

尝试这样的事情:

@property
def del_element(self, value):
    self._mylist.remove(value)

@property
def add_element(self,value):
    self._mylist.append(value)