对于上下文,我对类和Python一般都很陌生。
我有课程Bot
和课程BotSub
在Bot
我有self.driver
的内容,后来我致电BotSub()
。从BotSub
开始,如何致电Bot
self.driver
?
答案 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()
...