【发布时间】:2016-01-13 16:05:54
【问题描述】:
我开始使用 Python 3 进行 OOP,我发现 property 的概念非常有趣。
我需要封装一个私有列表,但是如何将这个范例用于列表?
这是我天真的尝试:
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)
当我尝试以下代码时,这与预期不符,甚至导致 python 崩溃。这是我希望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]
【问题讨论】:
-
prints 重要吗? -
@AnandSKumar 是的,因为它们实际上代表了对我使用
i和new的值执行的其他类成员的进一步更新。
标签: python list python-3.x indexing properties