gpt4 book ai didi

python list/dict 属性最佳实践

转载 作者:行者123 更新时间:2023-11-28 23:06:11 24 4
gpt4 key购买 nike

我有一个类对象,它存储一些属性,这些属性是其他对象的列表。列表中的每个项目都有一个标识符,可以使用 id 属性访问该标识符。我希望能够从这些列表中读取和写入,但也能够访问由其标识符键入的字典。让我用一个例子来说明:

class Child(object):
def __init__(self, id, name):
self.id = id
self.name = name

class Teacher(object):
def __init__(self, id, name):
self.id = id
self.name = name

class Classroom(object):
def __init__(self, children, teachers):
self.children = children
self.teachers = teachers

classroom = Classroom([Child('389','pete')],
[Teacher('829','bob')])

这是一个愚蠢的例子,但它说明了我正在尝试做的事情。我希望能够像这样与教室对象进行交互:

#access like a list
print classroom.children[0]
#append like it's a list
classroom.children.append(Child('2344','joe'))
#delete from like it's a list
classroom.children.pop(0)

但我也希望能够像访问字典一样访问它,并且当我修改列表时字典应该自动更新:

#access like a dict
print classroom.childrenById['389']

我知道我可以把它变成一个字典,但我想避免这样的代码:

classroom.childrendict[child.id] = child

我也可能有几个这样的属性,所以我不想添加像 addChild 这样的函数,反正感觉很不符合 Python 风格。有没有办法以某种方式对 dict 和/或 list 进行子类化,并使用我的类的属性轻松提供所有这些功能?我还想尽可能避免使用代码。

最佳答案

索引列表类:

class IndexedList(list):
def __init__(self, items, attrs):
super(IndexedList,self).__init__(items)
# do indexing
self._attrs = tuple(attrs)
self._index = {}
_add = self._addindex
for obj in self:
_add(obj)

def _addindex(self, obj):
_idx = self._index
for attr in self._attrs:
_idx[getattr(obj, attr)] = obj

def _delindex(self, obj):
_idx = self._index
for attr in self._attrs:
try:
del _idx[getattr(obj,attr)]
except KeyError:
pass

def __delitem__(self, ind):
try:
obj = list.__getitem__(self, ind)
except (IndexError, TypeError):
obj = self._index[ind]
ind = list.index(self, obj)
self._delindex(obj)
return list.__delitem__(self, ind)

def __delslice__(self, i, j):
for ind in xrange(i,j):
self.__delitem__(ind)

def __getitem__(self, ind):
try:
return self._index[ind]
except KeyError:
return list.__getitem__(self, ind)

def __getslice__(self, i, j):
return IndexedList(list.__getslice__(self, i, j))

def __setitem__(self, ind, new_obj):
try:
obj = list.__getitem__(self, ind)
except (IndexError, TypeError):
obj = self._index[ind]
ind = list.index(self, obj)
self._delindex(obj)
self._addindex(new_obj)
return list.__setitem__(ind, new_obj)

def __setslice__(self, i, j, newItems):
_get = self.__getitem__
_add = self._addindex
_del = self._delindex
newItems = list(newItems)
# remove indexing of items to remove
for ind in xrange(i,j):
_del(_get(ind))
# add new indexing
if isinstance(newList, IndexedList):
self._index.update(newList._index)
else:
for obj in newList:
_add(obj)
# replace items
return list.__setslice__(self, i, j, newList)

def append(self, obj):
self._addindex(obj)
return list.append(self, obj)

def extend(self, newList):
newList = list(newList)
if isinstance(newList, IndexedList):
self._index.update(newList._index)
else:
_add = self._addindex
for obj in newList:
_add(obj)
return list.extend(self, newList)

def insert(self, ind, new_obj):
# ensure that ind is a numeric index
try:
obj = list.__getitem__(self, ind)
except (IndexError, TypeError):
obj = self._index[ind]
ind = list.index(self, obj)
self._addindex(new_obj)
return list.insert(self, ind, new_obj)

def pop(self, ind=-1):
# ensure that ind is a numeric index
try:
obj = list.__getitem__(self, ind)
except (IndexError, TypeError):
obj = self._index[ind]
ind = list.index(self, obj)
self._delindex(obj)
return list.pop(self, ind)

def remove(self, ind_or_obj):
try:
obj = self._index[ind_or_obj]
ind = list.index(self, obj)
except KeyError:
ind = list.index(self, ind_or_obj)
obj = list.__getitem__(self, ind)
self._delindex(obj)
return list.remove(self, ind)

可以用作:

class Child(object):
def __init__(self, id, name):
self.id = id
self.name = name

class Teacher(object):
def __init__(self, id, name):
self.id = id
self.name = name

class Classroom(object):
def __init__(self, children, teachers):
self.children = IndexedList(children, ('id','name'))
self.teachers = IndexedList(teachers, ('id','name'))

classroom = Classroom([Child('389','pete')], [Teacher('829','bob')])

print classroom.children[0].name # -> pete

classroom.children.append(Child('2344','joe'))
print len(classroom.children) # -> 2
print classroom.children[1].name # -> joe
print classroom.children['joe'].id # -> 2344
print classroom.children['2344'].name # -> joe

p = classroom.children.pop('pete')
print p.name # -> pete
print len(classroom.children) # -> 1

编辑:我在一些异常处理中犯了一个错误(捕获 KeyError 而不是 IndexError);它是固定的。我将添加一些单元测试代码。如果您遇到任何其他错误,请告诉我!

关于python list/dict 属性最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5332841/

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