[英]Python - Can I import variables from another file as class variables?
[英]How to import global variables in python from a class module in another file?
我有一個文件,其中包含需要在主文件中使用的類定義和函數,以使文本更整潔。 但是,我在導入全局變量時遇到問題。
SO和其他資源中有很多信息,涉及如何在同一代碼中使函數變量成為全局變量,或者如何使用導入文件中的全局變量。 但是,如果變量屬於一個類的函數,則沒有有關如何從導入文件訪問變量的信息。
我將不勝感激如何做到或為什么不能做到。 由於我的情況需要使用全局變量,因此請跳過有關使用此類全局變量的危險性的講座。
編輯:很抱歉在原始帖子中沒有示例。 這是我的第一個。 以下是我要完成的示例。
假設我有一個包含以下內容的文件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
然后在我的主文本文件中執行以下操作:
from classes import HelixTools
ht = HelixTools()
v1 = some vector
v2 = some other vector
ht.calc_angle(v1,v2)
print(v1_v2_dot)
結果是未定義“ v1_v2_dot”。 我需要v1_v2_dot才能將其用作另一個函數的輸入。
這是一個有關如何訪問類屬性的示例(如果我了解您要正確執行的操作)。 假設您有一個名為“ 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
現在讓我們假設您想將該類導入到同一目錄中的另一個python文件中,並訪問該類的屬性。 您可以這樣做:
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
之所以可行,是因為__init__ magic方法中定義的變量是在首次調用Foo對象時立即初始化的,因此可以在訪問后立即訪問此處定義的屬性。 必須先調用bar()方法,然后才能訪問z屬性。 我制作了2個Foo對象,只是為了說明包括“自我”的重要性。 在變量前面,因為每個屬性都是特定於該特定類實例的。
我希望能回答您的問題,但是如果您提供了一些示例代碼來准確顯示您想要做什么,那將非常有幫助。
您可能應該使用class屬性來存儲此值。 注意,實現將取決於您的HelixTools
類的實際功能。 但是對於該示例,您可以使用如下所示的內容:
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)
接着:
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.