Vid*_*ain 2 python arrays object
当我在python中创建一个对象数组时,初始化为数组的值不是预期的
我定义的类是
class piece:
x = 0
y = 0
rank = ""
life = True
family = ""
pic = ""
def __init__(self, x_position, y_position, p_rank, p_family):
piece.x = x_position
piece.y = y_position
piece.rank = p_rank
piece.family = p_family
Run Code Online (Sandbox Code Playgroud)
当我初始化数组
pie = []
pie.append(piece(25, 25, "p", "black"))
pie.append(piece(75, 25, "p", "black"))
pie.append(piece(125, 25, "p", "black"))
print(pie[1].x)
Run Code Online (Sandbox Code Playgroud)
输出为125,预期输出为75
Mik*_*tty 10
您正在设置类属性,而不是将值分配给类的实例:
class piece:
def __init__(self, x_position, y_position, p_rank, p_family):
self.x = x_position
self.y = y_position
self.rank = p_rank
self.family = p_family
Run Code Online (Sandbox Code Playgroud)