Python 是否可以只导入选定的变量
我是python新手 我尝试只从另一个文件导入单个变量或其中的一些变量。Python 是否可以只导入选定的变量,python,variables,import,Python,Variables,Import,我是python新手 我尝试只从另一个文件导入单个变量或其中的一些变量。 我尝试从conf import SINGLE_变量中导入,但它给了我一个 ImportError:无法导入name'单个变量 也许用python的方式编写代码不是一个好主意,但我很好奇 如果可能的话 Thx只需确保您的变量是全局变量即可使用 hello1.py fname = "hello" lname = "world" from hello1 import fname print(fname) hello2.py
我尝试从conf import SINGLE_变量中导入
,但它给了我一个
ImportError:无法导入name'单个变量
也许用python的方式编写代码不是一个好主意,但我很好奇
如果可能的话
Thx只需确保您的变量是全局变量即可使用
hello1.py
fname = "hello"
lname = "world"
from hello1 import fname
print(fname)
hello2.py
fname = "hello"
lname = "world"
from hello1 import fname
print(fname)
输出
hello
与Python3.x配合使用只需确保您的变量是全局变量即可使用
hello1.py
fname = "hello"
lname = "world"
from hello1 import fname
print(fname)
hello2.py
fname = "hello"
lname = "world"
from hello1 import fname
print(fname)
输出
hello
与Python3.x配合使用好的,谢谢您的回答
我只是想说我想从一个类中导入我的变量……在这种情况下,导入必须在适当的方法中
有关内存,请参阅我的(工作)代码:
file1.py:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from file2 import Message
WORD_LIST = ["hello","bonjour","ola"]
Message(1)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Message:
def __init__(self, index):
from file1 import WORD_LIST
self._phrase = WORD_LIST[index] + " world"
def __str__(self):
return self._phrase
file2.py:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from file2 import Message
WORD_LIST = ["hello","bonjour","ola"]
Message(1)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Message:
def __init__(self, index):
from file1 import WORD_LIST
self._phrase = WORD_LIST[index] + " world"
def __str__(self):
return self._phrase
好的,谢谢你回答大家
我只是想说我想从一个类中导入我的变量……在这种情况下,导入必须在适当的方法中
有关内存,请参阅我的(工作)代码:
file1.py:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from file2 import Message
WORD_LIST = ["hello","bonjour","ola"]
Message(1)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Message:
def __init__(self, index):
from file1 import WORD_LIST
self._phrase = WORD_LIST[index] + " world"
def __str__(self):
return self._phrase
file2.py:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from file2 import Message
WORD_LIST = ["hello","bonjour","ola"]
Message(1)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Message:
def __init__(self, index):
from file1 import WORD_LIST
self._phrase = WORD_LIST[index] + " world"
def __str__(self):
return self._phrase
是的,这是可能的。错误消息说它在conf import SINGLE_VARIABLE
的conf
中找不到SINGLE_VARIABLE
是一种很好的编码风格,只要名为SINGLE_VARIABLE
的东西实际在conf
中,它就会工作。您可以使用print(dir(module))
或print来研究模块内容(帮助(模块))
。确保在函数外部声明了单变量。您能提供您的代码吗?是的,这是可能的。错误消息说它无法在conf
中从conf import SINGLE\u VARIABLE
中找到SINGLE\u VARIABLE
,这是一种很好的编码样式,只要名为SINGLE\u VARIABLE
的东西是actu,它就会工作在conf
中加入。您可以使用print(dir(module))
或print(help(module))
来研究模块内容。确保在函数外部声明单个变量。您能提供代码吗?