正确的实例化子类的方法?

时间:2013-10-02 16:27:44

标签: python class

所以我正在做一个小小的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类中使用它,与维度属性相同。实例化类ScreenGameMenager的正确方法是什么?

我关于super(),但是当我在子类中没有参数时,我没有找到关于如何实例化子类的大量信息。

2 个答案:

答案 0 :(得分: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
>>>

答案 1 :(得分: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