【问题标题】:Python pass variable from class in one file to another filePython将变量从一个文件中的类传递到另一个文件
【发布时间】:2017-06-27 12:00:16
【问题描述】:

我在两个文件中有以下代码:

操作1.py

class App_Name():
    def __init__(self):
        self.type_option = ""

    def Intro(self):
        self.type_option = input("Chose one option: ")
...

start = App_Name()
start.Intro()

menu.py

from operation1 import App_name

aP = App_Name()

if aP.type_option == 1:
    do smth
elif aP.type.type_option == 2:
   do smth 2

如果我输入 1,我希望从第一个 if 条件运行命令。当我尝试打印App_name.type_option 时,它似乎是空的。如何将aP.type_option 的值传递给 menu.py?

【问题讨论】:

  • option 只有 1 个“p”。您正在定义 2 个不同的变量...
  • 我在这里手动输入代码,没有复制 - 是错字
  • 问题:if aP.type_option == 1: 不可能发生:type_option 是 python 3 中的字符串。
  • 问题 #2:您创建了 2 个单独的实例。你必须在menu.py中做ap.Intro()

标签: class variables python-3.5


【解决方案1】:

startaP 是 2 个不同的实例。由于type_option 绑定到一个实例,start.type_option 包含输入(作为字符串),而aP.type_option 包含您在__init__ 方法中设置的空字符串。

删除 operation1 模块中的 start 实例化,否则在导入时会提示您!

然后修复menu.py如下:

from operation1 import App_name

aP = App_Name()
aP.Intro()

if aP.type_option == "1":
    do smth
elif aP.type.type_option == "2":
   do smth 2

(请注意,必须对字符串进行比较,因为 Python 3 input 返回字符串,不会像 python 2 input 那样评估文字)

【讨论】:

  • 如果我必须将 start.Intro() 保留在 operation1.py 中,我如何将 type_option 的值从 operation1.py 调用到 menu.py?
  • 试试operation1.start.type_option,在这种情况下你不需要menu.py中的实例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 2021-01-21
  • 2014-07-02
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
  • 2012-07-14
相关资源
最近更新 更多