Search code examples
pythonlistclassobjectattributes

How to print an attribute of an object from within a list


If I have a list in Python that contains objects with class attributes, how can I print the list of objects but only a specific attribute?

For example:

I have an object with the attribute of NAME with NAME being = to Cat. I have another object with the NAME attribute being = to Dog.

  • Both objects are in a list and I want to print all the objects.NAME only

Here is some example code (very poorly & quickly written)

class play_object():
    def __init__(self, weight, size, name):
        self.weight = weight
        self.size = size
        self.name = name

objects = []

car = play_object(6, 10, "Car")
cat = play_object(0.5, 1, "Cat")

objects.append(car)
objects.append(cat)

print(objects)

This outputs:

[<__main__.play_object object at 0x000001D0714053D0>, <__main__.play_object object at 0x000001D0712ACF90>]

Amending the code to have:

print(objects.name)

Results in the output:

Traceback (most recent call last):
  File "C:/Users//AppData/Local/Programs/Python/Python311/Test2.py", line 15, in <module>
    print(objects.name)
AttributeError: 'list' object has no attribute 'name'

So what is the correct way to just print the selected attribute from objects in the list?


Solution

  • Firstly you need to iterate elements in list. then you need to print each attributes of objects.

    for object in objects:
        print(i.name)
    

    Your wrong: Your are trying to get name of list. But your objects have name attribute instead of list. So you need to print name of objects