![](/img/trans.png)
[英]I have a list which has been created from another list. However, I do not want two names repeating after each other. How can I do that?
[英]I have two scripts of code and i want to import just one specific line from one into the other. How do i do it?
我想將一個特定的代碼行從一個腳本導入另一個腳本。 我不希望新代碼僅在一行中運行整個腳本。 我怎么做?
例如, from brcus import value
其中value等於完成的腳本中的數字,我想將該數字導入新腳本中,而舊腳本中的該行代碼為:“ value = 500”
每當您導入任何python模塊或軟件包並使用該模塊中的某些函數或值時,它都不會立即運行所有腳本。
你可以那樣做。
from old import value
a = value
如果使用命令導入
from package import value
價值將成為您新代碼的一部分
例如
源代碼
value = 500
other = 400
命運
from Source import value
print (value)
>>500
命運
from Source import value
print (other)
>>NameError: name 'other' is not defined
我建議將要導入的零件移動到單獨的模塊中,並將其導入到其使用的所有模塊中。
my_var.py
text = "Hello"
test.py
from my_var import text
def hello_friend(friend_name)
print(text + " " + friend_name)
main.py
from my_var import text
print(text)
您還可以在導入的模塊中設置環境變量並檢查其值
test.py
import os
if os.environ['only_new_str'] != str(True):
print("new_str is not calculated yet")
new_str = "Hello world"
if os.environ['only_new_str'] != str(True):
print("new_str calculated")
main.py
import os
os.environ['only_new_str'] = str(True)
import test
print(test.new_str)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.