Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8869297
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T17:27:23+00:00 2026-06-14T17:27:23+00:00

So I’m making a game, and all objects derive from one GameObject class, which

  • 0

So I’m making a game, and all objects derive from one GameObject class, which looks something like this;

class GameObject(pygame.sprite.DirtySprite):
    actions = dict()

    def __init__(self):
        pygame.sprite.DirtySprite.__init__(self)
        self.rect  = None
        self.state = None

    def update(self):
        if callable(self.__class__.actions[self.state]):
        #If this key has a function for its element...
            self.__class__.actions[self.state](self)

Now, I’m running into another issue with inheritance. Observe the class below, and the two that derive from it;

class Bullet(gameobject.GameObject):
    FRAME  = pygame.Rect(23, 5, 5, 5)
    STATES = config.Enum('IDLE', 'FIRED', 'MOVING', 'RESET')

    def __init__(self):
        gameobject.GameObject.__init__(self)
        self.image = config.SPRITES.subsurface(self.__class__.FRAME)
        self.rect  = self.__class__.START_POS.copy()
        self.state = self.__class__.STATES.IDLE

    actions = {
               STATES.IDLE   : None        ,
               STATES.FIRED  : start_moving,
               STATES.MOVING : move        ,
               STATES.RESET  : reset       ,
              }

class ShipBullet(bullet.Bullet):
    SPEED     = -8
    START_POS = pygame.Rect('something')

    def __init__(self):
        super(self.__class__, self).__init__()
        self.add(ingame.PLAYER)

class EnemyBullet(bullet.Bullet):
    SPEED     = 2
    START_POS = pygame.Rect('something else')

    def __init__(self):
        super(self.__class__, self).__init__()
        self.add(ingame.ENEMIES)

Every element of Bullet.actions (a static member, mind you) except for None is a function held within Bullet. Bullet is not meant to be created on its own; if this were C++, it would be an abstract class. So what happens is, Bullet‘s subclasses search through Bullet.actions every frame to decide what to do next, depending on their state (are they moving, were they just shot, etc.). However, since the elements of Bullet.actions are Bullet‘s own methods, its subclasses are executing those instead of their own extended versions (which call the parent methods). I don’t want to have to duplicate this dict of callbacks for memory usage reasons. So, I ask this; how can I have an instance of a subclass look through it’s parents dictionary full of callback methods, and execute their own version if it exists, and their parent’s version if it doesn’t?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T17:27:24+00:00Added an answer on June 14, 2026 at 5:27 pm

    One possible solution is to store the function’s name instead of direct references and using getattr to retrieve the correct reference:

    actions = {
               STATES.IDLE   : None          ,
               STATES.FIRED  : 'start_moving',
               STATES.MOVING : 'move'        ,
               STATES.RESET  : 'reset'       ,
              }
    
    [...]
    
    def update(self):
        method_name = self.__class__.actions[self.state]
        if method_name and callable(getattr(self, method_name)):
            getattr(self, method_name)(self)
    

    For a speedup, you can pre-compute this table when initializing the object:

    class Bullet(gameobject.GameObject):
    
        FRAME  = pygame.Rect(23, 5, 5, 5)
        STATES = config.Enum('IDLE', 'FIRED', 'MOVING', 'RESET')
    
        action_names = {
                         STATES.IDLE   : None          ,
                         STATES.FIRED  : 'start_moving',
                         STATES.MOVING : 'move'        ,
                         STATES.RESET  : 'reset'       ,
                        }
    
        def __init__(self):
            gameobject.GameObject.__init__(self)
            self.image = config.SPRITES.subsurface(self.__class__.FRAME)
            self.rect  = self.__class__.START_POS.copy()
            self.state = self.__class__.STATES.IDLE
    
            # Update actions table using getattr, so we get the correct
            # method for subclasses.
            self.actions = {}
            for state, method_name in self.action_names.items():
                if method_name and callable(getattr(self, method_name)):
                    self.actions[state] = getattr(self, method_name)
                else:
                    self.actions[state] = lambda self: None
    
    
        def update(self):
            self.actions[self.state]()
    

    Notice that since the code in __init__ uses getattr, it can be placed in Bullet.__init__ and merely extended by the other classes. As you already call the super constructor, there would be no need to change the extending classes or even annotate them.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
For some reason, after submitting a string like this Jack’s Spindle from a text
I would like to run a str_replace or preg_replace which looks for certain words
I have a text area in my form which accepts all possible characters from
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I have an autohotkey script which looks up a word in a bilingual dictionary
Does anyone know how can I replace this 2 symbol below from the string
I'm making a simple page using Google Maps API 3. My first. One marker
Let's say I'm outputting a post title and in our database, it's Hello Y’all
link Im having trouble converting the html entites into html characters, (&# 8217;) i

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.