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.

Upvotes: 4

Views: 32895

Answers (2)

317070
317070

Reputation: 847

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])

Upvotes: 1

pythondetective
pythondetective

Reputation: 336

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

Upvotes: 5

Related Questions