【问题标题】:Function calls to multiple different files in pythonpython中对多个不同文件的函数调用
【发布时间】:2018-04-19 13:10:57
【问题描述】:

我想用我自己的函数创建多个文件并将其存储为多个脚本文件。让它发挥作用的最佳方法是什么。 如何从另一个 python 脚本调用它?

例如,我在文件a.py、b.py 和c.py 中有文件a.py、b.py、c.py 和x.py。我想使用其他导入文件中的函数。

def a():
  print("Function a is called")
  print(c())
  return 1

b.py

def b():
  # Something
  print("function b is called.")
  return 2

c.py

def c():
  # de Something
  print("Function C is called.")
  print(b())
  return 3

print(a())

x.py

from a import *
from b import *
from c import *
print(a())
print(b())
print(c())

谢谢。

【问题讨论】:

  • 这样做的目的是什么?如果它们在同一个目录中,您可以使用os.sys() 调用它们吗?或者你有不同的用例?
  • 你贴的代码有什么问题?
  • 我遇到的情况是我有一个脚本,其中包含通过串行端口提问的功能。 TransmitCom(Com,"help") time.sleep(0.20) Error = 0 ReceiveCom(Com,"help", 200,"IGNORE")
  • 您有a 调用c 和c 调用b。如果你想这样做,那么a 需要导入c 并且c 需要导入b。但是,如果您希望 b 导入 a 您将有循环引用并且它不起作用。每个文件放置一个函数或类在编译语言中很常见,但在动态语言中效果不佳。

标签: python function python-import


【解决方案1】:

看起来不错。 函数 c() 应该像其他函数 a、b 一样返回一些值(整数)。 在 x.py 中,只需要导入即可,例如

x.py

import a
import b
import c
print(a())
print(b())
print(c())

确保所有缩进都正常

【讨论】:

  • 谢谢,但我的问题是,如果我运行 x.py,我在模块 c.py 中有错误。 NameError: 名称“a”未定义
猜你喜欢
  • 2021-04-22
  • 2014-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-27
  • 1970-01-01
  • 2013-03-17
  • 2018-07-27
相关资源
最近更新 更多