Skip to content Skip to sidebar Skip to footer

How To Access A Variable From A Function Which Is In Another File In Python

I am new to python. As part of my project, I am working with python2.7. I am dealing with multiple files in python. Here I am facing a problem to use a variable of particular funct

Solution 1:

So you have edited it quite a bit since I started writing about conventions so I have started again.

First, your return statement is out of indentation, it should be indented into the output method.

def output():
    a = "Hello"data = // some operationsreturndata

Second, the convention in Python regarding class names is CamelCase, which means your class should be called "Connect". There is also no need to add the round brackets when your class doesn't inherit anything.

Third, right now you can only use "data" since only data is returned. What you can do is return both a and data by replacing your return statement to this:

return a, data

Then in your second file, all you have to do is write a_received, data_received = connect.output()

Full code example:

file1.py

classConnect:

    def output():
        a = "Hello"data = "abc"return a, data

file2.py

from file1 import Connect

a_received, data_received = Connect.output()

# Print resultsprint(a_received)
print(data_received)

Fourth, there are other ways to combat this, like create instance variables for example and then there is no need for return.

file1.py

classConnect:defoutput(self):
        self.a = "Hello"self.data = "abc"

file2.py

from file1 import Connect

connection = Connect()
connection.output()

print(connection.a)
print(connection.data)

There is also the class variable version.

file1.py

classConnect:

    def output():
        Connect.a ="Hello"
        Connect.data = "abc"

file2.py

from file1 import Connect

Connect.output()

print(Connect.a)
print(Connect.data)

Eventually, the "right" way to do it depends on the use.

Solution 2:

One option you have is to return all the data you need from the function:

file1.py

classconnect():# Contains different definitionsdefoutput():
        a = "Hello"
        data = // some operations
        return a,data   # Return all the variables as a tuple

file2.py

from file1 import connect
c =connect()
a,data = c.output()
# Now you have local variables 'a'and'data'from output()

Post a Comment for "How To Access A Variable From A Function Which Is In Another File In Python"