is it possible to link scripts in python?

Yes, there is a way if the code of main file is inside a function.

Suppose the main script (file1.py):

def main():
  return "Hello world!"

if __name__ == "__main__":
  print(main())

Then inside the second script you can import and call function like:

import file1
print(file1.main())

Let’s go further.

Here we have a class inside the main script:

class myClass:
  def __init__(self):
    self.x = 10
    def getHello(self):
      return "Hello world!"

Now we can use the class from the main script like:

import file1
theClass = file1.myClass()
print(theClass.x)
print(theClass.getHello())

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top