[英]How to return a value from one python script to another?
file1.py
from processing file import sendfunction
class ban():
def returnhello():
x = "hello"
return x #gives reply a value of "hello replied" in processingfile
print(sendfunction.reply()) #this should fetch the value of reply from processingfile,right?
processingfile.py
from file1 import ban
class sendfunction():
def reply():
reply = (ban.returnhello() + " replied")
return reply
我似乎無法得到任何結果,任何幫助將不勝感激。
您需要在調用其member function
之前創建類ban
object
,如下所示
from file1 import ban
class sendfunction():
def reply(self): # Member methods must have `self` as first argument
b = ban() # <------- here creation of object
reply = (b.returnhello() + " replied")
return reply
或者,您將returnhello
方法作為static
方法。 然后,您不需要事先創建類的object
來使用。
class ban():
@staticmethod # <---- this is how you make static method
def returnhello(): # Static methods don't require `self` as first arugment
x = "hello"
return x #gives reply a value of "hello replied" in processingfile
BTW:
良好的編程習慣是,你總是用Capital
字母開始你的課程名稱。
函數和變量名稱應該是帶有下划線的小寫,因此returnhello()
應該是return_hello()
。 如前所述這里 。
假設我們有兩個文件A.py和B.py
A.py
a = 3
print('saying hi in A')
B.py
from A import a
print('The value of a is %s in B' % str(a))
在執行B.py時,您將獲得以下輸出:
└> python B.py
saying hi in A
The value of a is 3 in B
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.