-1

To better organize my code, I tried to create a constants class:

class Constants:
    def __init__(self):
        Constants.SCREEN_WIDTH = 1500
        Constants.SCREEN_HEIGHT = 800
        Constants.WINDOW_COLOR = (100, 100, 100)

        Constants.TICKRATE = 60
        Constants.GAME_SPEED = .35

        Constants.LINE_COLOR = (0, 0, 255)
        Constants.ALINE_COLOR = (0, 0, 0)

        Constants.BARRIER = 1
        Constants.BOUNCE_FUZZ = 0

        Constants.START_X = int(.5 * Constants.SCREEN_WIDTH)
        Constants.START_Y = int(.99 * Constants.SCREEN_HEIGHT)

        Constants.AIR_DRAG = .3

When I try to call one of the constants, such as on this line:

ball = Ball(Constants.START_X, Constants.START_Y)

I get this error: AttributeError: type object 'Constants' has no attribute 'START_X'

What am I doing wrong?

Alec
  • 8,529
  • 8
  • 37
  • 63

1 Answers1

1

Class members in python are defined like this:

class Constants:
    SCREEN_WIDTH = 1500
    SCREEN_HEIGHT = 800
    WINDOW_COLOR = (100, 100, 100)

    TICKRATE = 60
    GAME_SPEED = .35

    LINE_COLOR = (0, 0, 255)
    ALINE_COLOR = (0, 0, 0)

    BARRIER = 1
    BOUNCE_FUZZ = 0

    START_X = int(.5 * SCREEN_WIDTH)
    START_Y = int(.99 * SCREEN_HEIGHT)

    AIR_DRAG = .3

You can then access them using Constants.START_X etc.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • Thanks, I'm locked out of voting and accepting for a little while, so I'll +1/accept tomorrow. You don't need the `__init__()` – Alec Apr 16 '19 at 04:47