Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i access and object attribute inside a list of objects given certain index?

In other programming languages, to access attributes in of a class instance you just do:

print(Object.Attr)

and you do so in python as well, but how exactly you get a certain attribute at a certain index in a list of objects, normally i'd do this:

ListObj[i].attr

but the object is in a list. I want to access a specific index inside the list and pull the object attributes inside that index.

like image 843
Filippe Goncalves Marchezoni Avatar asked Sep 02 '25 17:09

Filippe Goncalves Marchezoni


2 Answers

In Python, to access object attribute the syntax is

<object instance>.<attribute_name>

In your case, [index].

As Paul said, use dir(<object_instance>[index]) to get all attribute, methods associated object instance.

You can also use for loop to iterate over

for <obj> in <object_list>:
    <obj>.<attribute_name>

Hope it helps

like image 109
pythondetective Avatar answered Sep 04 '25 05:09

pythondetective


You can access the dict (a.k.a Hashtable) of all attributes of an object with:

ListObj[i].__dict__

Or you can only get the names of these attributes as a list with either

ListObj[i].__dict__.keys()

and

dir(ListObj[i])
like image 34
317070 Avatar answered Sep 04 '25 07:09

317070