1

我希望有一个带有在其他方法中调用的方法的类,但我希望这些方法可以被覆盖并默认通过。有没有办法(很好地)做到这一点?

编辑:我对我将如何覆盖这些方法特别感兴趣。我试过了def setup(self): ...game.setup = setup。这有点工作,但它不能与“self”参数一起正常工作,抛出 setup() missing 1 required positional argument: 'self'

编辑2:我意识到我应该继承Game并覆盖子类中的方法。为什么我花了这么长时间我不知道。

如果我的话很愚蠢和令人困惑,这里有一些代码:

class Game(threading.Thread):
    def update(self):
        pygame.display.update()
        self.screen.fill(self.fillcolour)

    def setup(self):
        """Placeholder for setup"""
        pass

    def frame(self):
        """Placeholder for frame"""
        pass

    def handleInputs(self):
        """Placeholder for input handling"""

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.quit()

    def run(self):
        self.setup()

        while True:
            if self.FRAMERATE:
                self.clock.tick(self.FRAMERATE)

            self.frame()
            self.update()
            self.handleInputs()
4

2 回答 2

1

This is called the Template Method Pattern and your code is fine.

You probably want to call an overridable method for each event though and not override the entire handleInputs (or you'll have to reimplement the loop each time).

class Game(threading.Thread):
    def update(self):
        pygame.display.update()
        self.screen.fill(self.fillcolour)

    def setup(self):
        """Placeholder for setup"""
        pass

    def frame(self):
        """Placeholder for frame"""
        pass

    def handleEvent(self, event):
        """Placeholder for input handling"""
        pass

    def handleInputs(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.quit()
            self.handleEvent(event)

    def run(self):
        self.setup()

        while True:
            if self.FRAMERATE:
                self.clock.tick(self.FRAMERATE)

            self.frame()
            self.update()
            self.handleInputs()
于 2013-03-09T17:32:12.110 回答
1

我想你可以这样做:

class Whatever(object):
    def _placeholder(self,*args,**kwargs):
        """
        This function does nothing, but in a subclass, 
        it could be useful ...
        """
        return

    setup = _placeholder
    frame = _placeholder
    ...

这至少减少了样板代码......

于 2013-03-09T17:30:18.707 回答