I have some code to define a class in which the main entity is a dictionary. For example:
class MyDictionary:
def __init__(self):
self.__my_dict = {'a': 1,
'b': 2,
'c': 3}
def __getitem__(self, item):
return self.__my_dict[item]
def __len__(self):
return len(self.__my_dict)
def keys(self):
# ?
def items(self):
# ?
my_dict = MyDictionary
for key, value in my_dict.items():
print([key, value])
for key in my_dict.keys():
print(my_dict[key])
How should I define the member functions such that I can use the [], len(), keys(), items() operators on the class instance my_dict as if it were a dictionary?
#!/usr/bin/env python
class MyDictionary:
def __init__(self, my_dict):
self.my_dict = my_dict
def __getitem__(self, item):
return self.my_dict[item]
def __len__(self):
return len(self.my_dict)
def items(self):
return self.my_dict.items()
def keys(self):
return self.my_dict.keys()
def values(self):
return self.my_dict.values()
if __name__ == '__main__':
d = {'a': 1,'b': 2,'c': 3}
di = MyDictionary(d)
print(di.__len__())
print(di.items())
print(di.keys())
print(di.values())
print(di.__getitem__('b'))
output:
3
dict_items([('a', 1), ('b', 2), ('c', 3)])
dict_keys(['a', 'b', 'c'])
dict_values([1, 2, 3])
2
You can keep doing what you're doing with the __getitem__ and __len__ methods, and delegate the rest of the methods to the respective methods of __my_dict:
class MyDictionary:
def __init__(self):
self.__my_dict = {'a': 1,
'b': 2,
'c': 3}
def __getitem__(self, item):
return self.__my_dict[item]
def __len__(self):
return len(self.__my_dict)
def keys(self):
return self.__my_dict.keys()
def items(self):
return self.__my_dict.items()
my_dict = MyDictionary()
for key, value in my_dict.items():
print([key, value])
for key in my_dict.keys():
print(my_dict[key])
Note that you should instantiate an object of a class with parentheses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With