【问题标题】:How to import a global variable from one folder into another folder?如何将一个文件夹中的全局变量导入另一个文件夹?
【发布时间】:2021-05-18 11:39:01
【问题描述】:

在写到这里之前,我试图找到我的问题的答案,但我找不到。我的问题是如何在不初始化类的情况下将一个文件夹中的全局变量导入另一个文件夹。

举个例子

#folder1
#example1.py
class Example1(object):
    def __init__(self,var1, var2,var3): 
        self.var1 = var1
        self.var2 = var2
        self.var3 = var3

    def train_step():
        global tag
        tag = '1234'

第二个文件夹

#folder2
#example2.py

from ..folder1.example1 import Example1 
#here i need to use tag variable without initializing the Example1 class.

我知道没有实例化,我们不能使用任何类变量和函数,因为变量是全局的。所以,我只需要知道,有什么方法可以使用它吗?我不知道。

要实例化,我需要提供很多变量。这就是原因,我试图使用全局变量,只从另一个文件夹导入文件。

提前致谢

【问题讨论】:

    标签: python python-3.x oop


    【解决方案1】:

    您不能那样做,因为global tag 是在函数体内定义的,如果您不调用该函数,则不会执行该行。

    另一方面,类的主体“是”在创建类本身时执行的。那么为什么不将tag 定义为类变量呢?然后你可以通过类名访问它,而不需要从中获取实例。

    在example1.py中:

    class Example:
        tag = '1234
    

    在example2.py中:

    from ..folder1.example1 import Example1
    print(Example1.tag)
    

    【讨论】:

    • 我的类需要很多变量来实例化。所以我将变量设为全局变量。
    • @mariya 那你为什么不在 global 的类之外指定它们呢?也许我不明白你的目标是什么。
    【解决方案2】:

    我知道没有实例化,我们不能使用任何类变量...

    没有。我们确实可以在不初始化类的情况下访问类变量。

    Class methods 可以在您不需要创建类的实例来访问其属性时使用。使用@classmethod 装饰器来创建一个类方法。

    #folder1
    #example1.py
    class Example1(object):
        def __init__(self,var1, var2,var3): 
            self.var1 = var1
            self.var2 = var2
            self.var3 = var3
    
        @classmethod
        def train_step(cls):
            tag = '1234'
            return tag
    
    #folder2
    #example2.py
    
    from folder1.example1 import Example1
    TAG = Example1.train_step()
    

    这里,在example2 中,您无需创建类Example1 的实例即可访问tag 属性。

    也可以通过关注this answer 获得类似的结果。但是使用类方法的好处是可以给不同的方法赋予不同的标签,而不必为每个方法创建单独的全局变量。

    例子:

    class Example1:
        @classmethod
        def train_step(cls):
            tag = '1234'
            return tag
        
        @classmethod
        def train_step2(cls):
            tag = "9876"
            return tag
            
    print(Example1.train_step()) # prints 1234
    print(Example1.train_step2()) # prints 9876
    
    

    此外,您可以传入一个可选参数,以便方法train_step 也可以用于其他东西,而不仅仅是返回tag

    有点像:

     class Example1:
        @classmethod
        def train_step(cls, get_tag=False): # get_tag set as False by default 
            tag = "1234"
            if get_tag:
                return tag
            else:
                # Do stuff
    
    print(Example1.train_step(get_tag=True)) # prints 1234
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-12
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      • 1970-01-01
      • 2019-08-16
      相关资源
      最近更新 更多