Python用lis装饰属性setter

2024-06-25 08:27:06 发布

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

globalList = []
class MyList:
    def __init__(self):
        self._myList = [1, 2, 3]

    @property
    def myList(self):
        return self._myList + globalList
    @myList.setter
    def myList(self, val):
        self._myList = val

mL1 = MyList()
print("myList: ", mL1.myList)
mL1.myList.append(4)
print("after appending a 4, myList: ", mL1.myList)
mL1.myList.extend([5,6,"eight","IX"])
print("after extend, myList: ", mL1.myList)

结果:

myList:  [1, 2, 3]
after appending a 4, myList:  [1, 2, 3]
after extend, myList:  [1, 2, 3]

我面临的问题是mL1.myList.append(4)和mL1.myList.extend([5,6,“8”,“IX”])没有修改mL1对象中的myList属性。我怎样才能解决这个问题?


Tags: selfinitdefvalclassixprintafter
2条回答

我将对list进行子类划分,并重写一些方法:

import itertools

class ExtendedList(list):
    def __init__(self, other=None):
        self.other = other or []

    def __len__(self):
        return list.__len__(self) + len(self.other)

    def __iter__(self):
        return itertools.chain(list.__iter__(self), iter(self.other))

    def __getitem__(self, index):
        l = list.__len__(self)

        if index > l:
            return self.other[index - l]
        else:
            return list.__getitem__(self, index)

它应该适用于几乎所有的情况:

In [9]: x = ExtendedList([1, 2, 3])

In [10]: x
Out[10]: [1, 2, 3]

In [11]: x.append(9)

In [12]: x
Out[12]: [9, 1, 2, 3]

In [13]: x.extend([19, 20])

In [14]: x
Out[14]: [9, 19, 20, 1, 2, 3]

In [15]: sum(x)
Out[15]: 54

我为类对象定义了一个append()和一个extend()方法。它分别附加到成员myList和扩展成员myList。

global globalList  
globalList = []
class MyList():
    def __init__(self):
        self._myList = [1, 2, 3]

    @property
    def myList(self):
        return self._myList + globalList
    @myList.setter
    def myList(self, val):
        self._myList = val

    def append(self, val):
        self.myList = self.myList + [val]
        return self.myList  

    def extend(self, val):
        return self.myList.extend(val)


mL1 = MyList()
print("myList: ", mL1.myList)
mL1.append(4)
print("after appending a 4, myList: ", mL1.myList)
mL1.myList.extend([5,6,"eight","IX"])
print("after extend, myList: ", mL1.myList)

结果是

>>> 
('myList: ', [1, 2, 3])
('after appending a 4, myList: ', [1, 2, 3, 4])
('after extend, myList: ', [1, 2, 3, 4, 5, 6, 'eight', 'IX'])

相关问题 更多 >