【问题标题】:python pass method from classB as argument to classA then call a method within classA from the classB method that was passedpython将classB中的方法作为参数传递给classA,然后从传递的classB方法中调用classA中的方法
【发布时间】:2020-01-19 00:17:24
【问题描述】:

我知道标题听起来令人困惑,但请耐心等待。 我正在编写我的第一个游戏,我正在尝试为 AI 设置一个类(称为 AI_mode),我的 obj_creature 类可以使用它来获得生物实体需要的任何类型的 AI。我将 AI_mode 中的方法作为变量传递给 obj_creature。从 AI_mode 传递给 obj_creature 的方法从 obj_creature 类内部调用另一个方法。这是一些精简的代码:

class obj_creature:
    def __init__(self, npc_mode=None):
        self.npc_mode=npc_mode

    def move(self, word):
        print(word)


class AI_mode:
    def ai_move_left(self):
        self.owner.move("Hello World")


enemy_ai=AI_mode().ai_move_left
enemy_creature=obj_creature(npc_mode=enemy_ai) 


if enemy_creature.npc_mode:
    enemy_creature.npc_mode()

这段代码给出了错误:

self.owner.move("Hello World")
AttributeError: 'AI_mode' object has no attribute 'owner'

我很确定 .owner() 不是在那里使用的正确东西,因为我从未将 obj_creature 声明为所有者,但我不确定在其位置使用什么。当我尝试像这样声明 obj_creature 为 AI_mode 的所有者时:

class obj_creature:
    def __init__(self, npc_mode=None):
        self.npc_mode=npc_mode
        if npc_mode:
            npc_mode.owner=self

我得到这个错误:

npc_mode.owner=self
AttributeError: 'method' object has no attribute 'owner'

我的最终目标是轻松地将来自同一类的大量 AI 分配给任何种类的生物,并且以后能够使用相同的命令调用分配给它的任何 AI

【问题讨论】:

  • AI 应该拥有这个生物,而不是相反。

标签: python oop methods pygame components


【解决方案1】:

找到下面的代码设计:

class obj_creature:
    def __init__(self, npc_mode=None):
        self.npc_mode=npc_mode

    def move(self, word):
        print(word)


class AI_mode:
    def __init__(self, owner):
        self.owner = owner

    def ai_move_left(self):
        self.owner.move("Hello World")


enemy_creature=obj_creature()
enemy_ai=AI_mode(enemy_creature)
enemy_creature.npc_mode=enemy_ai.ai_move_left

if enemy_creature.npc_mode:
    enemy_creature.npc_mode()

【讨论】:

    猜你喜欢
    • 2014-05-06
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 2020-10-04
    相关资源
    最近更新 更多