Skip to content
Advertisement

Defining a classmethod outside of a class in Python [closed]

I am making a game with Pygame where there are going to be many different screens. I am making a class called Screen that will have custom screens made for you. I need each screen to have different events and triggers though, so I can’t just define one function in the class. I need separate functions for each screen which would mean that I need to define functions out side of the class definition for each screen. I don’t know if this is possible but it would be good to know. I have not gotten too far in yet but here is the code:

import pygame


class Screen:
    def __init__(self, size, bg_color, bg_image):
        self.size = size
        self.bg_color = bg_color
        self.bg_image = bg_image
        self.layers = []
        self.screen = pygame.display.set_mode(self.size)

    # some code was taken out here to save space (it was just some x y width and height getters and setters)

    def add_item(self, item, layer=None):
        if layer is None:
            self.layers.append(item)
        else:
            self.layers.insert(layer, item)

    def remove_item(self, item):
        self.layers.remove(item)

    def draw(self):
        self.screen.fill(self.bg_color)
        self.screen.blit(self.bg_image)

        for item in self.layers:
            self.screen.blit(item, item.pos)

Advertisement

Answer

I need each screen to have different events and triggers though

So you are searching for Inheritance. Read about Inheritance and Polymorphism in Python Use Screen as a base class. Derive different classes from Screen, where you can implement different behavior:

class Screen:
    def __init__(self, size, bg_color, bg_image):
        # [...]
  
    # [...]
class Screen_1(Screen):
    def __init__(self, size, bg_color, bg_image):
        super().__init__(size, bg_color, bg_image)

    def my_method():
        # do something
        # [...]
class Screen_2(Screen):
    def __init__(self, size, bg_color, bg_image):
        super().__init__(size, bg_color, bg_image)

    def my_method():
        # do something different
        # [...]
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement