Olivier Pons
Olivier Pons

Reputation: 15778

How to pass a class as a parameter and inherit methods

I've already read this but I would like to inherit of the methods of the class in parameter.

Example:

class TypeOfGame1(object):
    def get_max_players(self):
        return 2

class TypeOfGame2(object):
    def get_max_players(self):
        return 30

class Game(object):
    def __init__(self, game_cls):
        self.game = game_cls()

Then from this code above how could I do stuff like:

a = Game(TypeOfGame1)
a.get_max_players()  # should return 2
a = Game(TypeOfGame2)
a.get_max_players()  # should return 30

Upvotes: 3

Views: 124

Answers (2)

salparadise
salparadise

Reputation: 5805

if I understand correctly how about using __getattr__ to proxy your class?

n [2]: class Game(object):
   ...:     def __init__(self, game_cls):
   ...:         self.game = game_cls()
   ...:     def __getattr__(self, other):
   ...:         return getattr(self.game, other)
   ...:

In [7]: g = Game(TypeOfGame1)

In [8]: g.get_max_players()
Out[8]: 2

In [11]: g = Game(TypeOfGame2)

In [12]: g.get_max_players()
Out[12]: 30

Upvotes: 1

Selcuk
Selcuk

Reputation: 59184

You can't do this, but you can use the game object instead:

>>> a = Game(TypeOfGame1)
>>> a.game.get_max_players()
2
>>> a = Game(TypeOfGame2)
>>> a.game.get_max_players()
30

or implement the methods in the game object as proxies in your Game class:

class Game(object):
    ...
    def get_max_players(self):
        return self.game.get_max_players()

Upvotes: 1

Related Questions