我已经阅读了this,但我想继承参数中类的方法。
示例:
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()
然后从上面的代码中我怎么能做到这样的事情:
a = Game(TypeOfGame1)
a.get_max_players() # should return 2
a = Game(TypeOfGame2)
a.get_max_players() # should return 30
答案 0 :(得分:1)
您无法执行此操作,但您可以改为使用game
对象:
>>> a = Game(TypeOfGame1)
>>> a.game.get_max_players()
2
>>> a = Game(TypeOfGame2)
>>> a.game.get_max_players()
30
或将game
对象中的方法实现为Game
类中的代理:
class Game(object):
...
def get_max_players(self):
return self.game.get_max_players()
答案 1 :(得分:1)
如果我正确理解如何使用__getattr__
代理您的课程?
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