1

所以我正在做一个小的 Pygame 程序,我试图以体面的方式构建这些东西,这就是我坚持的地方。

class Screen(object):
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.SURFACE = 10 # I need this attribute

class GameMenager(Screen):
    def __init__(self) # Do I need to put the parameters of the super class here?
        super().__init__() # What to put in these parantheses?

我想获取SURFACE属性,以便可以在 Game 类中使用它,与维度属性相同。Screen实例化类和的正确方法是什么GameMenager

super()当我在子类中没有参数时,我很高兴但实际上并没有找到有关如何实例化子类的太多信息。

4

2 回答 2

3

super像这样使用:

class Screen(object):
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.SURFACE = 10

class GameMenager(Screen):
    def __init__(self, width, height):
        super(GameMenager, self).__init__(width, height)

现在,您可以访问Screen.SURFACE

>>> x = GameMenager(1, 2)  # I just picked 1 and 2 for width and height.
>>> x.SURFACE
10
>>>
于 2013-10-02T16:34:07.783 回答
1

你不想GameMenager成为一个子类,在这里。相反,您希望将屏幕实例传递给GameMenager实例:

class GameMenager(object):
    def __init__(self, screen):
        self.screen = screen
        self.screen.SURFACE #can do w/e you want with it
    #for example:
    def print_surface(self):
        print self.screen.SURFACE

并按如下方式实例化它:

>>> s = Screen(640, 480) 
>>> gm = GameMenager(s)
>>> gm.print_surface()
10
于 2013-10-02T16:46:02.183 回答