如何将值从一个python脚本返回到另一个?

时间:2018-11-29 07:03:12

标签: python python-3.x python-import cross-reference

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

我似乎无法真正获得任何结果,将不胜感激。

2 个答案:

答案 0 :(得分:2)

您需要先创建类object的{​​{1}},然后按以下方式调用他的ban

member function

或者,您将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()。如here所述。

答案 1 :(得分:0)

假设我们有两个文件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