首页 > 解决方案 > 如何将一个python脚本的值返回到另一个?

问题描述

文件1.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?

处理文件.py

from file1 import ban
class sendfunction():
    def reply():
        reply = (ban.returnhello() + " replied")
        return reply

我似乎无法得到任何结果,任何帮助将不胜感激。

标签: pythonpython-3.xpython-importcross-reference

解决方案


您需要在调用他之前创建object类,如下所示banmember 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()应该是return_hello(). 正如这里提到的。


推荐阅读