简体   繁体   中英

Placeholder class methods Python 3

I wish to have a class with methods which are called in its other methods, but I want those methods to be overwritable and to pass by default. Is there a way to (nicely) do this?

EDIT: I'm particularly interested in how exactly I would go about overwriting the methods. I've tried def setup(self): ... , game.setup = setup . This works somewhat but it doesn't work properly with the "self" parameter, throwing setup() missing 1 required positional argument: 'self'

EDIT 2: I've realised that I should subclass Game and overwrite the methods in the subclass. Why it took me so long I do not know.

In case my words were stupid and confusing, here's some code instead:

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()

I suppose you could do something like:

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
    ...

This cuts down on the boiler plate code at least...

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM