使用导入文件中的变量?

Use variables from importing file?

假设我有一个有助于网络连接的变量(例如:API 访问令牌),我想在我正在导入的模块中使用它(用于扩展现有功能),有没有办法在不添加新的 class 或初始化方法的情况下将该变量传递给导入的脚本?

例如:

脚本一(performer.py):

import telepot
import botActions # Possibly adding an argument here?

botActions.sendMessage("locationID", "message")

accessToken = "SAMPLE"

脚本二(botActions.py):

import botApiWrapper

def sendMessage(locationID, text):
    bot.sendMessage(locationID, text)
    print("Message sent to %g: %t".format(g=locationID, t=text))

bot = botApiWrapper.Bot(sys.argv[0])

那么有没有一种方法可以将变量从第一个脚本传递到第二个脚本,或者我是否必须定义一个在导入文件后调用的初始化函数?

执行此类操作的规范方法是从其他文件定义初始化函数。而不是 bot = botApiWrapper.Bot(sys.argv[0]),尝试

def newbot(arg):
    bot = botApiWrapper.Bot(arg)
    return bot

然后从您的其他模块调用该函数。

如果需要state来操作,定义一个class.

class Bot(object):
    def __init__(self, arg):
        self.arg = arg
    def sendMessage(self, locationId, text):
        print "Using arg %s to send message to location %s with text %s" % \
            (self.arg, locationId, text)

...此后您可以根据需要初始化任意数量的机器人:

import botApiWrapper

botA = botApiWrapper.Bot("A")
botA.sendMessage("foo", "bar")

botB = botApiWrapper.Bot("B")
botB.sendMessage("baz", "qux")