Python:如何从另一个类访问实例变量?

时间:2018-06-02 10:50:39

标签: python

从概念上讲:我想从其他类

访问某个类中定义的实例变量

我的案例:我想从我的Alien类

访问Human Class中定义的self.x实例变量

为什么?:我正在创造一个太空入侵者游戏,其中有2个宇宙飞船(人类),而外星人正在下雨',目标是躲避那些外星人。对于与2艘船相对应的人类,我将有2个物体。在我的外星人类中有一个部分,它检测它是否在2个宇宙飞船中的任何一个(第二个代码块)的碰撞区域内。所以基本上是因为“自我”和“自我”。变量是每艘船的实例变量,如果我能以某种方式在我的外星人类中访问它,那么任何异形物体都能够检测到宇宙飞船的碰撞(因为self.x代表每个宇宙飞船的x坐标)。 p>

class Human:

    y = display_height * 0.8
    width = 120
    x_change = 0

    def __init__(self, image, initpos, left, right):
        self.image = image
        self.x = display_width * initpos
        self.left = left
        self.right = right

    def run(self):
        global gameExit
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameExit = True
            if event.type == pygame.KEYDOWN:
                if event.key == self.left:
                    if self.x > 0:
                        self.x_change = -8
                    else:
                        self.x_change = 0
                elif event.key == self.right:
                    if self.x < display_width - Human.width:
                        self.x_change = 8
                    else:
                        self.x_change = 0
            if event.type == pygame.KEYUP:
                if event.key == self.left or event.key == self.right:
                        self.x_change = 0
        gameDisplay.blit(self.image, (self.x, Human.y))
        self.x += self.x_change

human1 = Human(pygame.image.load('human.png'), 0.5, pygame.K_LEFT, pygame.K_RIGHT)
human2 = Human(pygame.image.load('human2.png'), 0.3, pygame.K_a, pygame.K_d)

class Alien:

    height = 120
    width = 80
    x = random.randrange(width, (display_width - width))
    y = -100

    def __init__(self, image, speed, hp):
        self.image = image
        self.speed = speed
        self.hp = hp

    def run(self):
        gameDisplay.blit(self.image, (self.x, self.y))
        self.y += self.speed

    def checkpos(self):
        global points
        if self.y > display_height:
            self.y = 0 - Alien.height
            self.x = random.randrange(Alien.width, display_width - Alien.width)
            points += 1
  

所以这就是问题开始的地方Human.y工作正常,因为y是一个类变量,它保持静态,因为人类船只只在水平轴上变化。但是x是Human的一个实例变量:我不能使它成为一个类变量,因为不需要做多人游戏模式,那里将有2艘船,所以每个人类对象必须分别控制。所以我需要以某种方式从我在下面的if语句中的Human:class中访问即时变量self.x

        if Human.y < self.y + Alien.height:
            print("y cross alien")
            if self.x < ("need to access instance variable self.x FROM HUMAN class") < self.x + Alien.width or self.x < ("same issue") + Human.width < self.x + Alien.width:
                print("x cross alien")

alien1 = Alien(pygame.image.load('alien1.png'), 7, 3)
alien2 = Alien(pygame.image.load('alien2.png'), 8, 4)
alien3 = Alien(pygame.image.load('alien3.png'), 9, 5)

0 个答案:

没有答案