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,"eight","IX"])不会修改mL1对象中的_myList属性。我该如何解决这个问题呢?
append()
应该添加到_myList
(这意味着值不会像预期的那样添加到末尾)还是globalList
?无论哪种方式,很明显这不起作用,因为返回的值是通过连接两个其他列表生成的新列表。扩展它不会以某种方式进行修改。 - Gareth LattyMyList
直接实现__getitem__()
、append()
等方法使其本身就像一个序列会更有意义,并且也更容易实现。 - Gareth Latty