If we want to create the same type of game entity over and over again (for example we need to create lots of enemy robot in our game) then it is better for us to create a base class first and then create the subclass from that base class. The subclass will have all the methods and properties from it’s base class plus it’s own method and property.
The base class on the other hand will derive from the python object class.
class GameEntity(object): def __init__(self, entity_id): self.id = entity_id def __str__(self): return "Entity id is %d" % (self.id)
Below subclass will derive from the base class.
from game_entity import GameEntity class RobotEntity(GameEntity): def __init__(self, entity_id): GameEntity.__init__(self, entity_id) self.strength = 50
Please take note that we need to call the __init__ method of the base class with below command.
If you create another module and run it with below script then we will get
from robot_entity import RobotEntity if __name__ == "__main__": robot_entity = RobotEntity(1) print(robot_entity) print("Robot strength is %s" % robot_entity.strength)
the below outcome.
Entity id is 1
Robot strength is 50
Notice that the first print command above will trigger the __str__ method of the base class (GameEntity class) to return the “Entity id is 1” string which will later get printed out on the screen!