您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

带有列表的Python装饰属性设置器

带有列表的Python装饰属性设置器

我为类对象定义了方法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'])
python 2022/1/1 18:49:38 有364人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶