Search code examples
pythonoopsubclassmultiple-inheritance

Python: how to implement multiple-inheritance?


New to oop. Writing in Python 3.

I am developing a multiplayer game. These are the classes I need:

  • a class 'server' - which is the main entry point from which all starts
  • a class 'game', that contains the game logic
  • a class 'gameroom' to allow multiple simultaneous games to run
  • a class 'player' with all the players details
  • a class 'session' which is the combination of player and game, containing player related info while playing

diagram of classes

It seems obvious that session should be a child of both player and gameroom. However, how does an instance of session know which instance of gameroom and player are its parents?

Suppose:

  • I have 5 player instances with playerIDs 1,2,3,4 and 5
  • I have 2 intances of gameroom with roomIDs 1 and 2.

Now I want an instance of 'session' for playerID = 2 and roomID = 2. How do I 'pass' the roomID and playerID to the new instance of session?

Is this the correct implementation? Or can I somehow implicitly create an instance of session without needing to save player and room in a variable?

from player import player
from room import room

class session(player,room):
    def __init__(self, player: player, room: room):
        self.point = 0
        self.player = player
        self.room = room
        print('player {} has joined room {}'.format(player.id,room.id))

Solution

  • Inheritance is not the right tool here. You should just pass a player and a room instance to the __init__ method of session.

    Inheritance is used to model extensions of classes. If one class inherits another, e.g. Car inherits Vehicle and you instantiate a Car object with car = Car(), car is also an instance of Vehicle.

    You can read more on this topic in the application section of the wikipedia article on inheritance.