在Python中从主文件创建和访问Settings类

时间:2017-03-12 23:50:40

标签: python class inheritance

我正在尝试创建一个外星人入侵游戏,但我遇到了一个障碍,让我的主文件从我的设置类导入设置。下面是我的代码,首先是我的alien_invasion主文件,然后是我的设置类:

主要脚本

import sys

import pygame

from settings import Settings

def run_game():
    #Initialize game and create a screen object.
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))

    #Start the main loop for the game.
    while True:

        #Watch for keyboard and mouse events.
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        #Redraw the screen during each pass through the loop.
        screen.fill(ai_settings.bg_color)

        #Make the most recently drawn screen visible
        pygame.display.flip()

run_game()

同一目录中的设置类

class Settings():
    """A class to store all for Alien Invasion."""

    def __int__(self):
        """Initialize the game's settings."""
        #Screen settings
        self.screen_width = 1200
        self.screen_height = 800
        self.bg_color (230, 230, 230)

尝试运行时,我得到以下内容:

Traceback (most recent call last):
  File "alien_invasion.py", line 28, in <module>
    run_game()
  File "alien_invasion.py", line 12, in run_game
    (ai_settings.screen_width, ai_settings.screen_height))
AttributeError: 'Settings' object has no attribute 'screen_width'

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

输入错误导致此问题,您在SELECT DISTINCT a.nom_voie, b.nom_voie, ST_Intersection(a.geom, b.geom) 课程i中遗漏了Settings

为了澄清,Python中的缩写__init__代表Integer数据类型。 int是&#34;初始化&#34;的缩写。

答案 1 :(得分:0)

我相信您可以使用以下方法解决此问题:

来自设置导入*

只要您没有任何重叠变量,并且settings.py和main.py位于同一目录中,这应该可以。

相关问题