gpt4 book ai didi

python - 在 Python 中创建列表属性

转载 作者:行者123 更新时间:2023-12-02 21:11:35 25 4
gpt4 key购买 nike

我开始使用 Python 3 进行 OOP,我发现属性的概念非常有趣。

我需要封装一个私有(private)列表,但是如何将这种范例用于列表?

这是我天真的尝试:

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]

最佳答案

import collections


class PrivateList(collections.MutableSequence):
def __init__(self, initial=None):
self._list = initial or []

def __repr__(self):
return repr(self._list)

def __getitem__(self, item):
print("Accessed element {}".format(item))
return self._list[item]

def __setitem__(self, key, value):
print("Set element {} to {}".format(key, value))
self._list[key] = value

def __delitem__(self, key):
print("Deleting element {}".format(key))
del self._list[key]

def __len__(self):
print("Getting length")
return len(self._list)

def insert(self, index, item):
print("Inserting item {} at {}".format(item, index))
self._list.insert(index, item)


class Foo(object):
def __init__(self, a_list):
self.list = PrivateList(a_list)

然后运行这个:

foo = Foo([1,2,3])
print(foo.list)
print(foo.list[1])
foo.list[1] = 12
print(foo.list)

输出:

[1, 2, 3]
Accessed element 1
2
Set element 1 to 12
[1, 12, 3]

关于python - 在 Python 中创建列表属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33144460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com