Python 修复依赖循环

我正在使用 python 开发游戏。


游戏中的 AI 使用玩家拥有的变量,反之亦然。


例如:


class Player():

    def __init__(self, canvas...):

        self.id = canvas.create_rectangle(...)

        ...

    def touching_AI(self):

        aipos = canvas.coords(AI object)

        pos = canvas.coords(self.id)

        ...


    #the function above checks if the player is touching the AI if it 

    #is, then call other functions


this = player(canvas...)


class AI():

   def __init__(self, canvas...):

       self.id = canvas.create_rectangle(...)

   def chase_player(self):

       playerpos = canvas.coords(this.id)

       pos = canvas.coords(self.id)

       ...

       # a lot of code that isn't important

显然,Python 说玩家类中的 AI 对象没有定义。两个类都依赖于另一个来工作。但是,一个还没有定义,所以如果我把一个放在另一个之前,它会返回一个错误。虽然可能只有这两个函数有一个解决方法,但还有更多我没有提到的函数。


总之,有没有办法(pythonic 或非 pythonic)在创建对象之前使用和/或定义它(即甚至制作更多文件)?


阿晨1998
浏览 233回答 3
3回答

神不在的星期二

你不而是使用参数class Player():    def __init__(self, canvas...):        self.id = canvas.create_rectangle(...)        ...    def touching(self,other):        aipos = canvas.coords(other.object)        pos = canvas.coords(self.id)        ...    #the function above checks if the player is touching the AI if it     #is, then call other functionsclass AI():   def __init__(self, canvas...):       self.id = canvas.create_rectangle(...)   def chase(self,player):       playerpos = canvas.coords(player.id)       pos = canvas.coords(self.id)然后player = Player(canvas...)ai  = AI(...)ai.chase(player)player.touching(ai)但更好的是定义一个基础对象类型来定义你的接口class BaseGameOb:     position = [0,0]     def distance(self,other):         return distance(self.position,other.position)class BaseGameMob(BaseGameOb):     def chase(self,something):         self.target = something     def touching(self,other):         return True or False那么你所有的东西都从这里继承class Player(BaseGameMob):      ... things specific to Playerclass AI(BaseGameMob):      ... things specific to AIclass Rat(AI):    ... things specific to a Rat type AI

LEATH

您没有依赖循环问题。但是,你有以下问题,您正在尝试使用 AI 对象,但您没有在任何地方创建该对象。它需要看起来像,foo = AI() #creating the object bar(foo) #using the object周围的语法错误canvas.coords(AI object)。调用函数的方式是foo(obj)没有类型。在定义函数时,您可以选择提及类型,例如 def foo(bar : 'AI'):你可以相互依赖类的证明,https://pyfiddle.io/fiddle/b75f2de0-2956-472d-abcf-75a627e77204/

杨魅力

您可以在不指定类型的情况下初始化一个并在之后分配它。Python 会假装每个人都是成年人,所以..例如:class A:    def __init__(self, val):        self.val = val        self.b = Noneclass B:    def __init__(self, a_val):        self.a = A(a_val)a_val = 1b = B(1)a = b.aa.b = b
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python