tehcanemc2 tehcanemc2 - 12 days ago 6
Python Question

Need to look through a class object without changing it

Alright, lets suppose I have a class called Tab and that class has a method that takes in keys and values of dictionaries and and makes it into a huge dictionary.

class Tab():

def __init__(self):
if not 'table' in dir(self):
self._table = {}

def add_table(self, key, value):
self._table[key] = value


Now if i were to have a function and a dictionary

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()


And if I were to run this it would run fine, but if I did this,

new_test = test['A']


It would crash. I know I can fix this by converting the object back into a dictionary, but i need the type to be the Tab class(the one i defined earlier).

How can I do this?

Answer

To make a Tab instance behave like a dictionary, you can override __getitem__(self, item), __setitem__(self, key, value) and __repr__(self) methods within Tab class:

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))

The output(sequentially):

['A', 'B', 'C']
{'B': ['D', 'E', 'F'], 'A': ['A', 'B', 'C'], 'C': ['G', 'H', 'I']}
<class '__main__.Tab'>