简体   繁体   English

如何从另一个文件中的类模块导入python中的全局变量?

[英]How to import global variables in python from a class module in another file?

I have a file that contains the class definitions and functions I need to use in my main file to make the text cleaner. 我有一个文件,其中包含需要在主文件中使用的类定义和函数,以使文本更整洁。 However, I'm having a problem with imported global variables. 但是,我在导入全局变量时遇到问题。

There is plenty of information at SO and other resources regarding how to make function variables global within the same code or how to use the global variables from an imported file. SO和其他资源中有很多信息,涉及如何在同一代码中使函数变量成为全局变量,或者如何使用导入文件中的全局变量。 However, there is no information on how to access a variable from an imported file if the variable belongs to a function belonging to a class. 但是,如果变量属于一个类的函数,则没有有关如何从导入文件访问变量的信息。

I would appreciate any help on how to do it or why it cannot be done. 我将不胜感激如何做到或为什么不能做到。 Please skip the lecture on the dangers of using global variables like this as my situation requires such use. 由于我的情况需要使用全局变量,因此请跳过有关使用此类全局变量的危险性的讲座。

Edit: Sorry for not having an example in the original post. 编辑:很抱歉在原始帖子中没有示例。 It's my first one. 这是我的第一个。 Below is an example of what I'm trying to accomplish. 以下是我要完成的示例。

Let's say I have a file classes.py that contains: 假设我有一个包含以下内容的文件classes.py:

class HelixTools():
    def calc_angle(v1, v2):
    v1_mag = np.linalg.norm(v1)
    v2_mag = np.linalg.norm(v2)

    global v1_v2_dot
    v1_v2_dot = np.dot(v1,v2)
    return v1_v2_dot

Then in my main text file I do: 然后在我的主文本文件中执行以下操作:

from classes import HelixTools

ht = HelixTools()
v1 = some vector
v2 = some other vector
ht.calc_angle(v1,v2)
print(v1_v2_dot)

The result is "v1_v2_dot" not defined. 结果是未定义“ v1_v2_dot”。 I need v1_v2_dot to use it as the input of another function. 我需要v1_v2_dot才能将其用作另一个函数的输入。

Here's an example of how you can access class attributes (if I understand what it is you want to do correctly). 这是一个有关如何访问类属性的示例(如果我了解您要正确执行的操作)。 Lets imagine you have a python file called "Test_class.py" that contains the following code: 假设您有一个名为“ Test_class.py”的python文件,其中包含以下代码:

class Foo(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def bar(self):
        self.z = self.x + self.y

Now lets imagine you want to import this class into another python file in the same directory, and access attributes of that class. 现在让我们假设您想将该类导入到同一目录中的另一个python文件中,并访问该类的属性。 You would do this: 您可以这样做:

from Test_class import Foo

# Initialize two Foo objects
test1 = Foo(5, 6)
test2 = Foo(2, 3)

# Access the x and y attributes from the first Foo object
print(test1.x)  # This will print 5
print(test1.y)  # This will print 6

# Access the x and y attributes from the second Foo object
print(test2.x)  # This will print 2
print(test2.y)  # This will print 3

# Access the z attribute from the first Foo object  
test1.bar()
print(test1.z)  # This will print 11

# Access the z attribute from the second Foo object
test2.bar()
print(test2.z)  # This will print 5

This works because variables defined in the __init__ magic method are initialized as soon as the Foo object is first called, so the attributes defined here can be access immediately after. 之所以可行,是因为__init__ magic方法中定义的变量是在首次调用Foo对象时立即初始化的,因此可以在访问后立即访问此处定义的属性。 The bar() method has to be called before you can access the z attribute. 必须先调用bar()方法,然后才能访问z属性。 I made 2 Foo objects just to show the importance of including "self." 我制作了2个Foo对象,只是为了说明包括“自我”的重要性。 in front of your variables, in that each attribute is specific to that particular class instance. 在变量前面,因为每个属性都是特定于该特定类实例的。

I hope that answers your question, but it would be very helpful if you provided some example code to show exactly what it is you want to do. 我希望能回答您的问题,但是如果您提供了一些示例代码来准确显示您想要做什么,那将非常有帮助。

You should likely use a class attribute to store this value. 您可能应该使用class属性来存储此值。 Note that the implementation will depend on what your class HelixTools really does. 注意,实现将取决于您的HelixTools类的实际功能。 But for the example, you could use something like this: 但是对于该示例,您可以使用如下所示的内容:

import numpy as np

class HelixTools():

    def __init__(self):
        # Initialize the attribute so you'll never get an error calling it
        self.v1_v2_dot = None

    def calc_angle(self, v1, v2):       # Pass self as first argument to this method
        v1_mag = np.linalg.norm(v1)
        v2_mag = np.linalg.norm(v2)
        # Store the value in the attribute
        self.v1_v2_dot = np.dot(v1,v2)

And then: 接着:

from classes import HelixTools

ht = HelixTools()
v1 = some vector
v2 = some other vector
ht.calc_angle(v1,v2)    # This will not return anything
print(ht.v1_v2_dot)     # Access the calculated value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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