【问题标题】:How do I access the variable inside a class method from another python file?如何从另一个 python 文件访问类方法中的变量?
【发布时间】:2023-01-26 16:25:43
【问题描述】:

我有两个 python 文件 main.pyconftest.py。我想从 contest.py 访问 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

比赛.py

from main import Test

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

【问题讨论】:

    标签: python selenium


    【解决方案1】:

    您的代码中存在一些错误,但本质上,要访问变量saved_dir,您必须将其定义为类Test 的属性,然后实例化该类的对象。

    在您的代码中,saved_dir 是方法 test_setup 的局部变量,因此在该上下文之外不可见。

    我向您展示了 2 个可能的正确文件:

    文件 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:SeleniumInsights	imestamp}".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
    

    请注意: 不要直接使用之前的代码,因为在main.py我已经根据我的环境调整了new_dir的值(请看/home/frank/Selenium/Insights/timestamp/而不是你的D:SeleniumInsights imestamp)。

    文件 contest.py:

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

    如果您想直接访问属性saved_dir而不使用方法get_saved_dir()不是很面向对象) 文件contest.py 变为:

    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()
    

    【讨论】:

    • 感谢您的解释和替代方案。它对我很有效。
    【解决方案2】:

    变量必须声明为属于类

    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:SeleniumInsights	imestamp}".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
    

    然后调用它

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

    【讨论】:

    • 谢谢,@surge10。调用变量时完全有意义。感谢帮助
    猜你喜欢
    • 2014-10-10
    • 2015-01-21
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 2020-07-15
    • 1970-01-01
    相关资源
    最近更新 更多