如何调用python类列表对象

时间:2013-06-06 17:58:11

标签: list class object python-2.7

class Ship:

    def __init__(self, pos, vel, angle, image, info):
        self.pos = [pos[0],pos[1]]
        self.vel = [vel[0],vel[1]]


def keydown(key):

    global current_key

    current_key=simplegui.KEY_MAP['down']

    pos_increment=15
    posx=Ship.shipx
    posy=Ship.shipy

    print current_key
    print posx,posy

错误是AttributeError:'Ship'对象没有属性'shipx'。请帮助

2 个答案:

答案 0 :(得分:2)

您必须在以下情况下实例化您的课程:

ship1 = Ship( pos, vel, angle, image, info)

之后,您可以使用类方法和属性:

posx, posy = ship1.pos

根据我们的评论,我认为这符合您的需求:

class Ship:

    def __init__(self, pos, vel, angle, image, info):
        self.pos = list(pos)
        self.vel = list(vel)

    def move(self, key):
        if key=='left':  self.pos[0] -= self.vel[0]
        if key=='right': self.pos[0] += self.vel[0]
        if key=='down':  self.pos[1] -= self.vel[1]
        if key=='up':    self.pos[1] += self.vel[1]


#example
ship1 = Ship( (0,0), (10,10), angle=None, image=None, info='')

def keystroke(key):
    global current_key
    ship1.move(key)

我不确定simplegui是如何工作的,但通过这种方式,您可以有效地映射所有击键可能性。此外,假设速度(vel)告知每次击键需要更改的像素数。

答案 1 :(得分:1)

在访问它们之前,您必须首先定义shipx和shipy,或者改为使用pos变量:

class Ship:
    def __init__(self, pos, vel, angle, image, info):
        self.pos = pos
        self.vel = vel

# create instance of your ship
ship = Ship(pos, vel, angle, image, info)

def keydown(key):
    global current_key

    current_key = simplegui.KEY_MAP['down']

    pos_increment = 15
    # change y-position of the ship on key press
    ship.pos[1] += pos_increment