Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 获取对象的上下文_Python_Oop_Python 3.x_Introspection - Fatal编程技术网

Python 获取对象的上下文

Python 获取对象的上下文,python,oop,python-3.x,introspection,Python,Oop,Python 3.x,Introspection,我正在用Python编写一个游戏。玩家角色和敌人角色都是Person的实例。字符可以具有幂,属于幂类Power。当角色在战斗中使用异能时,异能对象需要知道谁拥有该异能(以便应用该异能的任何效果)。我如何才能让Power对象知道它的人是谁 一个显而易见的解决方案是包含一个creation参数,该参数存储对人员的引用。然而,这有几个问题;一个是,任何Power方法都可能需要访问该变量,这变得很尴尬,因为我已经向每个方法传递了一堆参数 我宁愿有一种“聪明”的解决方案,允许对象“向上”查看它在哪里。有类

我正在用Python编写一个游戏。玩家角色和敌人角色都是
Person
的实例。字符可以具有幂,属于幂类
Power
。当角色在战斗中使用异能时,
异能
对象需要知道谁拥有该异能(以便应用该异能的任何效果)。我如何才能让
Power
对象知道它的
人是谁

一个显而易见的解决方案是包含一个creation参数,该参数存储对
人员的引用。然而,这有几个问题;一个是,任何
Power
方法都可能需要访问该变量,这变得很尴尬,因为我已经向每个方法传递了一堆参数


我宁愿有一种“聪明”的解决方案,允许对象“向上”查看它在哪里。有类似的东西吗?

不清楚对象是如何交互的,但下面是一个选项的最小示例:

def Power():

    def use(self, person):
        # do whatever


def Person():

    def __init__(self, power):
        self.power = power

    def use_power(self):
        self.power.use(self)

这为
Person
中的
Power
提供了一个接口,并在
使用
d时将
Person
显式地传递给
Power

好的,我以前没有这样做过。非常简单明了,但结构也很好。似乎是要走的路。。。