如何将类作为参数传递并继承方法

时间:2022-09-24 23:20:25

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

2 个解决方案

#1


1  

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

如果我正确理解如何使用__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

#2


1  

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:

或者将游戏对象中的方法实现为Game类中的代理:

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

#1


1  

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

如果我正确理解如何使用__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

#2


1  

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:

或者将游戏对象中的方法实现为Game类中的代理:

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