Evan Theis
Evan Theis

Reputation: 47

python - Issue using classes imported from a module

My assignment is to make a game, were supposed to have multiple modules to avoid clutter in one script. I'm having an issue with import a variable from one of the modules. So far I have a settings one, and a main one. The settings is pretty simple and goes:

class Settings():
def __init__(self):
    self.screen_width = 1920
    self.screen_height = 1080
    self.bg_color = (230, 230, 230)

Pretty simple, yet when I try to reference these variables it says "Unresolved attribute reference 'screen_width' for class 'Settings'

main goes as this:

import sys, pygame
from game_settings import Settings

def run_game():
    #Initialize the game and create the window
    pygame.init()
    screen = pygame.display.set_mode((Settings.screen_width,Settings.screen_height), pygame.FULLSCREEN)
    pygame.display.set_caption("Alien Invasion")

while True:

    #Listening for events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
             sys.exit()
    screen.fill(Settings.bg_color)
    pygame.display.flip()

run_game()

I thought maybe this would be a PyCharm issue, but found that it does the same thing in IDLE so what would be the correct way to import the variables?

Thanks for taking the time to read this!

Upvotes: 0

Views: 52

Answers (3)

pp_
pp_

Reputation: 3489

Both files have to be in the same folder and you have to create an instance of your Settings class. Then you can access the properties of your instance.

main.py:

from game_settings import Settings
s = Settings()
print(s.bg_color)

game_settings.py:

class Settings():
    def __init__(self):
        self.screen_width = 1920
        self.screen_height = 1080
        self.bg_color = (230, 230, 230)

When you run main.py, the output will be:

(230, 230, 230)

Upvotes: 0

Nick
Nick

Reputation: 7431

You need to create an instance of the Settings object: s = Settings()

Usage: s.bg_color, etc.

OR

Alter your Settings class like so and the properties are accessible statically:

class Settings():
    screen_width = 1920
    screen_height = 1080
    bg_color = (230, 230, 230)

Upvotes: 0

Blckknght
Blckknght

Reputation: 104712

You need to create an instance of your Settings class, since the attributes you set up in its __init__ method are instance attributes.

Try something like this:

def run_game():
    my_settings = Settings() # create Settings instance
    pygame.init()
    screen = pygame.display.set_mode((my_settings.screen_width, # lookup attributes on it
                                      my_settings.screen_height),
                                     pygame.FULLSCREEN)
    # ...

Upvotes: 2

Related Questions