如何调用调用类的属性

时间:2016-12-31 02:23:36

标签: python

对于上下文,我对类和Python一般都很陌生。

我有课程Bot和课程BotSub

Bot我有self.driver的内容,后来我致电BotSub()。从BotSub开始,如何致电Bot self.driver

1 个答案:

答案 0 :(得分:1)

您必须将对Bot对象(在self参数上)的引用传递给BotSub类,并且必须使用它来回调Bot类上的方法{1}}对象。

例如:

class Bot(object):
   def __init__(self):
       self.botsub = BotSub(self)

   def driver(self):
       ...

   def update(self):
       self.botsub.dothings()

class BotSub(object):
   def __init__(self, bot):
       self.bot = bot

   def dothing(self):
       self.bot.driver()

或者,您不需要将父Bot实例作为BotSub上的属性保存 - 只要在其上调用需要引用机器人的方法时,只需将其作为参数传递:

...
class Bot(object):
   ...
   def update(self):
       self.botsub.dothings(self)

class BotSub(object):
   ...
   def dothings(self, bot):
        bot.driver()
        ...