在Python中,如何从其他模块访问在主模块中创建的实例?

2024-04-19 01:04:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我不太懂OOP和Python。。。你知道吗

下面是一个关于我的问题的例子:

我的主模块中有一个类对象

# main.py
#---------

class MyRobot():

    def __init__(self):
        self.move = 0

    def walk(self):
        self.move += 5

    def botInfo(self):
        # In my case,
        # I can only address track.howFar to my main module
        import track
        getInfo = track.howFar
        print getInfo()


if __name__ == '__main__':
    bot = MyRobot()
    bot.walk()
    bot.botCMD()

还有另一个模块

# track.py
#---------
def howFar():
    return bot.move # How??

我需要从track.py获取bot对象中的move

这可能吗?你知道吗

我该怎么办??你知道吗

----更新----

我知道这个例子很奇怪。。。你知道吗

实际上我在研究python-telegram-bot的命令处理程序

请原谅我漏掉了很多细节

因为我觉得我的问题和它自己没什么关系。你知道吗

如果我浪费了你的时间,我向你道歉。。。你知道吗


Tags: 模块对象pyselfmovemainmydef
3条回答
import main
bot = main.myRobot() # bot.move

from main import myRobot
bot = myRobot() # bot.move

def howFar(robot_instance):
    return robot_instance.move

howFar(bot) # passing instance

正如jornsharpe在评论中提到的,下面将抛出一个ImportError。你知道吗

from main import bot

相反,我们必须导入类,然后在新文件中生成对象。你知道吗

from main import myRobot

bot = myRobot()    

def howFar():
    return bot.move

print(howFar())

输出

0

第一部分是将class myRobot移动到robot.py(或myrobot.py)的位置主.py. 你知道吗

下一步将取决于您的程序是如何编写的。不太理想的做法是在机器人.py到一个全局变量,然后可以从导入该模块的所有内容中访问该变量。你知道吗

也许第二个不太理想的是有一个类变量,比如

class myRobot():
    _my_robot = None

    @classmethod
    def MakeRobot(cls):
        if cls._my_robot is None:
            cls._my_robot = cls() #cls is `class myRoboto`

        return cls._my_robot

从那里你可以打电话myRobot.MakeRobot()一次创建一个新实例,对MakeRobot()的任何后续调用都将返回相同的实例。你知道吗

更理想的解决方案是,在脚本的实际主函数中,创建一个myRobot实例,并在需要的地方传递它。你知道吗

def run_program():
    robot = myRobot()

    while True: #or however your script runs
        #do robot move logic
        howFar(robot)

与此无关,我建议总是将类名大写,因为一般约定告诉其他人MyRobot是一个类,而myRobotmy_robot是一个变量。你知道吗

相关问题 更多 >