2016-11-27 89 views
1

好的,讓我們假設我有一個名爲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': ['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類(我之前定義的類)。

我該怎麼做?

+0

你是什麼意思'崩潰'?你有錯誤信息嗎?始終顯示有問題的完整錯誤消息(Traceback)。 – furas

+0

請參閱[__getitem__](https://docs.python.org/3/reference/datamodel.html#object.__getitem__)和[__setitem__](https://docs.python.org/3/reference/datamodel.html #object .__ setitem__) – furas

回答

2

爲了使Tab實例的行爲就像一本字典,你可以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']} 
<class '__main__.Tab'> 
0

爲什麼你過分複雜化事情呢?爲什麼不繼承dict對象,並使用update方法。

或甚至更好從collections模塊繼承UserDict

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'] 

而且最好是通過在OBJ功能read_table

相關問題