python - 在导入函数中引用 python 对象

标签 python object import

我有两个 .py 脚本文件。 “主”脚本将导入第二个包含杂项“辅助”函数的脚本。

在主脚本中,我为 SPI 接口(interface)设置了一个对象。我想在导入的文件中直接使用 SPI 接口(interface)编写函数。我对此一窍不通,并尝试以各种方式编写和传递,但总是出错。

主脚本.py

import helperfunctions.py as helper

spi = spidev.SpiDev()
spi.open(0, 0)

response = spi.xfer([ ... some data ...])  #this works when
                                           #called from mainscript.py

helper.sendOtherStuff()  #this doesn't work (see helper script below)

helperfunctions.py

def sendOtherStuff():
   #need to somehow reference 'spi.' object from mainscript.py file 
   otherData = ([... some different data ...])
   resp = spi.xfer([otherData])  #this fails because helperfunctions
                                 #apparently doesn't know spi. object
   return resp

关于全局变量值,我也经常有同样的一般性问题。我确信有一种“更好”的方法可以做到这一点,但出于现在的方便,我经常希望在 mainscript.py 中定义一些全局变量,然后在 helperfunctions.py 的函数中引用这些全局变量。我想不出办法做到这一点。走另一条路很容易——在 helperfunctions.py 中声明全局变量,然后从 mainscript.py 中引用它们作为 helper.variableName,但我不知道如何走另一条路。

非常感谢任何方向。谢谢。

最佳答案

据我所知,最简单的做法是将 spi 对象作为参数传递给辅助函数:

def sendOtherStuff(spi):
    otherData = ([... some different data ...])  
    return spi.xfer([otherData]) 

传入后,您可以在函数体中对其调用方法。我删除了您的变量分配,因为它看起来多余。

关于python - 在导入函数中引用 python 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39239398/

相关文章:

java - 如何在 ofbiz 应用程序中添加 servlet-api.jar?

Python 脚本失败,出现 ('Connection aborted.' , ConnectionResetError(104, 'Connection reset by peer' ))

Javascript 对象构造函数和 boolean 变量

c# - 在循环中动态创建对象

web-services - hybris中的核心数据、基本数据和样本数据有什么区别?

Python,导入模块进行测试

python - numpy中的局部线性近似

python - 如何获取字典元组的最大值

python - 我可以手动 ssh,但不能通过脚本 - 权限被拒绝(公钥)

javascript - for循环中对象中每个键的返回值