Python 需要查看类对象而不更改它
好的,让我们假设我有一个叫做Tab的类,这个类有一个方法,它接受字典的键和值,并将它变成一个巨大的字典Python 需要查看类对象而不更改它,python,dictionary,Python,Dictionary,好的,让我们假设我有一个叫做Tab的类,这个类有一个方法,它接受字典的键和值,并将它变成一个巨大的字典 class Tab(): def __init__(self): if not 'table' in dir(self): self._table = {} def add_table(self, key, value): self._table[key] = value 现在如果我有一个函数和一本字典 dic = {'A': ['
class Tab():
def __init__(self):
if not 'table' in dir(self):
self._table = {}
def add_table(self, key, value):
self._table[key] = value
现在如果我有一个函数和一本字典
dic = {'A': ['A', 'B','C'], 'B':['D', 'E','F']}
def read_table():
table = Tab()
for key in dic:
table.add_table(key, dic[key])
return table
test = read_table()
如果我来做这件事会很好但如果我做了
new_test = test['A']
它会崩溃。我知道我可以通过将对象转换回字典来解决这个问题,但是我需要类型为Tab类(我之前定义的那个)
如何实现这一点?要使
选项卡
实例的行为类似于字典,您可以在选项卡
类中重写getitem(self,item)
、setitem(self,key,value)
和repr(self)
方法:
class Tab():
def __init__(self):
if not 'table' in dir(self):
self._table = {}
def add_table(self, key, value):
self._table[key] = value
def __getitem__(self, item):
return self._table[item]
def __setitem__(self, key, value):
self._table[key] = value
def __repr__(self):
return self._table.__repr__()
dic = {'A': ['A', 'B','C'], 'B':['D', 'E','F']}
...
# read_table() function declaration (omitted)
...
test = read_table()
new_test = test['A'] # accessing dict element
test['C'] = ['G','H','I'] # setting a new dict element
print(new_test)
print(test) # printing Tab instance as a dict
print(type(test))
输出(按顺序):
['A','B','C']
{'B':['D','E','F'],'A':['A','B','C'],'C':['G','H','I']}
为什么要把事情复杂化?为什么不继承dict
对象,并使用update
方法
或者更好地从模块继承
最好在
read\u table
函数中传递obj。什么是crash
?你收到错误信息了吗?始终显示有问题的完整错误消息(回溯)。请参阅和
['A', 'B', 'C']
{'B': ['D', 'E', 'F'], 'A': ['A', 'B', 'C'], 'C': ['G', 'H', 'I']}
<class '__main__.Tab'>
from collections import UserDict
class Tab(UserDict):
pass
dic = {'A': ['A', 'B','C'], 'B':['D', 'E','F']}
def read_table(dic):
table = Tab()
table.update(dic)
return table
read_table(dic).data['A']