-1

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.

Gipo Company
  • 13
  • 1
  • 5
  • 1
    sure, just implement `__getitem__` – juanpa.arrivillaga Apr 29 '22 at 17:27
  • Can you please see if this answers your question? https://stackoverflow.com/questions/43627405/understanding-getitem-method – cadolphs Apr 29 '22 at 17:27
  • Probably a duplicate of: https://stackoverflow.com/questions/41686020/python-custom-class-indexing – juanpa.arrivillaga Apr 29 '22 at 17:28
  • 1
    It is possible. You do it by subclassing `dict` and overriding `__getattr__()` to call `__getitem__()`. I've seen it done by programmers who reckon that emulating Lua tables in Python is nicer than using Python dictionaries as-is. I've never seen an attempt that didn’t have bugs or gotchas. I won't attempt to write a full implementation because (a) I don't know how to avoid the gotchas and (b) it's a very bad idea. Do you really *need* to do it? – BoarGules Apr 29 '22 at 17:37

1 Answers1

1

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
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218