Home > database >  How do I access the variable inside a class method from another python file?
How do I access the variable inside a class method from another python file?

Time:10-25

I have two python files main.py and conftest.py. I want to access a variable inside the method of main.py from contest.py. I have tried a bit, but I know it's wrong as I get a syntax error in the first place. Is there any way to do this? main.py

class Test():

    def test_setup(self):
        #make new directory for downloads
        new_dir = r"D:\Selenium\Insights\timestamp}".format(timestamp=datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
        # print(new_dir)
        if not os.path.exists(new_dir):
            os.makedirs(new_dir)
            saved_dir=new_dir

conftest.py

from main import Test

def newfunc():
    dir=Test.test_setup()
    print(dir.saved_dir)

CodePudding user response:

In the file contest.py I think you have to change the instruction dir=Test.test_setup() with the instruction:

dir=Test().test_setup()

With the last instruction you create an instance of class Test so you can invoke the method test_setup().

CodePudding user response:

Variable must be declared as belonging to the class

class Test():

  def __init__(self):
    self.new_dir = ""
    self.saved_dir = ""

  def test_setup(self):
    #make new directory for downloads
    self.new_dir = r"D:\Selenium\Insights\timestamp}".format(timestamp=datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
    # print(self.new_dir)
    if not os.path.exists(self.new_dir):
      os.makedirs(self.new_dir)
      self.saved_dir=self.new_dir

Then calling it

def newfunc():
    dir=Test().test_setup()
    print(dir.saved_dir)
  • Related