无法创建常量类

时间:2019-04-16 04:41:16

标签: python 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

当我尝试调用常量之一时,例如在此行上:

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

我收到此错误:AttributeError: type object 'Constants' has no attribute 'START_X'

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

python中的类成员的定义如下:

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

然后您可以使用Constants.START_X等访问它们。