I need to create a class whose object will return the same values when
test_class.test_variable
and
test_class['test_variable']
Please let me know if this is possible and if so, how.
CodePudding user response:
You can use getattr
to lookup an attribute by name, and use that to implement __getitem__
for your class.
class test:
def __init__(self, var):
self.var = var
def __getitem__(self, s):
return getattr(self, s)
>>> t = test(5)
>>> t.var
5
>>> t['var']
5