【发布时间】:2022-01-25 09:22:30
【问题描述】:
我有一个名为 Civilizations 并初始化为的对象列表
Civilizations = []
我还有一个文明类和母舰类
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)
打印 (a) 结果给我们两次 <__main__.Mothership object at 0x0000029412E240A0>,而 x 最终看起来像 [300,300]。有没有办法遍历对象并获取它们的各个属性?我试图让 x 看起来像 [300, 350]。
感谢您的帮助!
【问题讨论】:
-
mothership是Civilization的类属性,由类的每个实例共享。您需要一个实例属性,因此请改为在__init__()中创建该列表。