Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I can't really seem to get any results, any help would be appreciated.

like image 268
belligerentbeagle Avatar asked Jun 28 '26 06:06

belligerentbeagle


1 Answers

You need to create object of class ban before calling his member function as follows

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

OR, you make returnhello method as static method. Then you don't need to create an object of class beforehand to use.

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: Good programming practice is that, you always start you class name with Capital Letter.
And function and variable names should be lowercase with underscores, so returnhello() should be return_hello(). As mentioned here.

like image 143
Oli Avatar answered Jun 30 '26 21:06

Oli