简体   繁体   中英

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

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)

There are some errors in your code, but essentially, to access to the variable saved_dir you have to define it as an attribute of the class Test , and after that instantiate an object of that class.

In your code saved_dir is a local variable of the method test_setup so is not visible outside of that context.

I show you the 2 possible correct files:

File main.py

from datetime import datetime
import os

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

  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'))
    timestamp=datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
    self.new_dir = "/home/frank/Selenium/Insights/timestamp/" + timestamp 
    # print(new_dir)
    if not os.path.exists(self.new_dir):
      os.makedirs(self.new_dir)
      self.saved_dir = self.new_dir
      
  def get_saved_dir(self):
    return self.saved_dir

Pay attention : don't use directly the previous code because in main.py I have adjusted the value of new_dir according to my environment (see /home/frank/Selenium/Insights/timestamp/ instead of your D:\Selenium\Insights\timestamp ).

File contest.py:

from main import Test

def newfunc():
    test_class = Test()
    test_class.test_setup()
    print(test_class.get_saved_dir())

newfunc()

If you want to access to the attribute saved_dir directly without the use of method get_saved_dir() ( not very object oriented ) the file contest.py becomes:

from main import Test

def newfunc():
    test_class = Test()
    test_class.test_setup()
    # access directly to attribute saved_dir (not properly Object Oriented)
    print(test_class.saved_dir)

newfunc()

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM