类从错误的文件调用属性

问题描述 投票:0回答:1

我收到错误 - AttributeError:“User_input_responses”对象没有属性“screen”。 我相信在我的 Ship() 文件中 self.screen = game.screen 错误地查看 User_input_responses 而不是查看 Alien_Invasion 来访问屏幕。不知道如何解决?

主文件 -

import pygame 
from ship_movement import User_input_responses
from settings import Settings
from ship_test import Ship

class Alien_Invasion:


    def __init__(self):
        
        pygame.init()
        self.settings = Settings()
        #screen
        self.screen = pygame.display.set_mode((self.settings.screen_width , self.settings.screen_height))
        pygame.display.set_caption(("Alien Invader"))
        self.bg_color = self.settings.bg_color

        self.clock = pygame.time.Clock()
        self.ship = Ship(self)
        self.movement = User_input_responses()
  

            
    def update_screen(self):
        pygame.display.flip()
        self.screen.fill(self.bg_color)
        self.ship.blitme()





    def game(self):
        while True:
            self.movement.user_input_reactions()
            self.ship.ship_movement()
            self.update_screen()
            self.clock.tick(60)


if __name__ == '__main__':
    game_launcher = Alien_Invasion()
    game_launcher.game()

文件调用属性 -

import pygame 
from settings import Settings

class Ship:

    def __init__(self, game):
        
        self.settings = Settings()
        self.screen = game.screen
        self.screen_rect = self.screen.get_rect()

        self.image = pygame.image.load("images/ship.bmp")
        self.rect = self.image.get_rect()

        self.rect.center = self.screen_rect.center
        self.x = float(self.rect.x)
        self.y = float(self.rect.y) 

出现错误的文件

import pygame
import sys
from ship_test import Ship

class User_input_responses:

    def __init__(self):
        self.ship = Ship(self)
        



    def user_input_reactions(self):

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            
            elif event.type == pygame.KEYDOWN:
                self.keydown(event)

            elif event.type == pygame.KEYUP:
                self.keyup(event)
python class methods pygame attributeerror
1个回答
0
投票
class User_input_responses:
    def __init__(self):
        self.ship = Ship(self)

__init__
类的
User_input_responses
方法声明一个
Ship
对象并将其自身作为参数传递。

class Ship:
    def __init__(self, game):
        self.settings = Settings()
        self.screen = game.screen

并且

__init__
类的
Ship
方法期望
game
参数具有
screen
属性。

但是

game
User_input_responses
的实例,它没有
screen
属性。

© www.soinside.com 2019 - 2024. All rights reserved.