Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to make a class with functions dictionary

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading