Skip to content
Advertisement

How can I get attributes of induvidual items in a list of Objects in Python?

I have a list of objects known as Civilizations and initialized as

Civilizations = []

I also have a class Civilization and class Mothership as

class Civilization():
    name = "Default Civilization"
    hero_count = 1
    builder_count = 20
    mothership = []
    def __init__(self, param, name, hero_count):
        self.param = param
        self.name = name
        self.hero_count = hero_count

class Mothership():
    name = ""
    coord_x = 0.0
    coord_y = 0.0
    coord_size = 50
    def __init__(self, name, coord_x, coord_y):
        self.name = name
        self.coord_x = coord_x
        self.coord_y = coord_y

red = Civilization(10, "RED", 1)
blue = Civilization(12, "BLUE", 1)
Civilizations.append(red)
Civilizations.append(blue)

orange = Mothership("Stasis", 300.0, 500.0)
red.mothership.append(orange)
yellow = Mothership("Prime", 350.0, 550.0)
blue.mothership.append(yellow)    

x = []
y = []
s = []
n = []

print(Civilizations)
for t in Civilizations:
    a = t.mothership[0]
    print(a)
    # x.append(a.coord_x)
    # y.append(a.coord_y)
    # s.append(a.coord_size)
    # n.append(a.name)
    print(n)

print(x)

Printing (a) gives us <__main__.Mothership object at 0x0000029412E240A0> twice as a result, and x ends up looking like [300,300]. Is there a way to iterate over the objects and obtain their individual attributes? I am trying to get x to look like [300, 350].

Thank You for your help!

Advertisement

Answer

Issue is with the below two lines of code.

for t in Civilizations:
    a = t.mothership[0]

mothership list in Civilizations class will be appended with two objects. Civilizations.mothership = [ obj_orange, obj_yellow ]

Since your mothership list having two values in index of 0 & 1. In your code you are using only index 0 to retrieve the value throughout the loop. Your loops runs twice and returns the same object (obj_orange) twice.

Either you have to retrieve both the values from index 0 & 1 like below

for t in Civilizations:
    a = t.mothership[0]
    b = t.mothership[1]

Or simply you can use ‘enumerate’ which is very good practice in situations like where you don’t know the number of elements in a list.

for i, t in enumerate(Civilizations):
    print(t.mothership[i])

where i = index number , t = value

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement