0

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?

buran
  • 13,682
  • 10
  • 36
  • 61
ryant
  • 13
  • 2
  • Does this answer your question? [How to extract from a list of objects a list of specific attribute?](https://stackoverflow.com/questions/677656/how-to-extract-from-a-list-of-objects-a-list-of-specific-attribute). Check also https://stackoverflow.com/q/12933964/4046632 – buran Jan 11 '23 at 08:58

1 Answers1

0

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

  • Thank you so much - I am quite a novice when it comes to Python I suppose, I will give this a try :) – ryant Jan 11 '23 at 12:44