Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Access object attributes as in a dictionary

>>> my_object.name = 'stuff'
>>> my_str = 'name'
>>> my_object[my_str] # won't work because it's not a dictionary :)

How can I access to the fields of my_object defined on my_str ?

like image 719
Pierre de LESPINAY Avatar asked Jan 27 '12 15:01

Pierre de LESPINAY


People also ask

Can we use object as key in dictionary Python?

Dictionaries in PythonAlmost any type of value can be used as a dictionary key in Python. You can even use built-in objects like types and functions.

Can an object be a value in a dictionary Python?

Takeaway: A dictionary key must be an immutable object. A dictionary value can be any object.


1 Answers

You can provide support for the [] operator for objects of your class by defining a small family of methods - getitem and setitem, principally. See the next few entries in the docs for some others to implement, for full support.

like image 137
Laizer Avatar answered Oct 19 '22 02:10

Laizer