带有列表的Python装饰属性设置器 [英] Python decorating property setter with list

查看:77
本文介绍了带有列表的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,"eight","IX"])不会修改ml1对象中的_myList属性.我该怎么做才能解决问题?

The problem I am facing is that mL1.myList.append(4) and mL1.myList.extend([5,6,"eight","IX"]) do not modify the _myList attribute in the mL1 object. How could I do to resolve the problem?

推荐答案

我为类对象定义了方法append()和方法extend().它分别追加到成员myList并扩展成员myList.

I define a method append() and a method extend() for the class object. It respectively appends to member myList and extends member 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装饰属性设置器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆