我开始使用Python 3进行OOP,我发现property
的概念确实很有趣。在Python中创建列表属性
我需要封装一个私人列表,但我怎么能用这个范例的列表?
这里是我的幼稚的尝试:
class Foo:
""" Naive try to create a list property.. and obvious fail """
def __init__(self, list):
self._list = list
def _get_list(self, i):
print("Accessed element {}".format(i))
return self._list[i]
def _set_list(self, i, new):
print("Set element {} to {}".format(i, new))
self._list[i] = new
list = property(_get_list, _set_list)
预期这并不表现甚至让蟒蛇崩溃,当我尝试下面的代码。这是我想Foo
展示的虚拟行为:
>>> f = Foo([1, 2, 3])
>>> f.list
[1, 2, 3]
>>> f.list[1]
Accessed element 1
2
>>> f.list[1] = 12
Set element 1 to 12
>>> f.list
[1, 12, 3]
是'print's重要? –
@AnandSKumar是的,因为它们实际上代表了我使用'i'和'new'的值执行的其他类成员的进一步更新。 –