2016-04-28 126 views
0

我試圖訪問我在Python中的另一個模塊內的一個函數中創建的變量來繪製圖表,但是Python無法找到它們。 繼承人一些示例代碼:調用另一個模塊中的變量python

class1: 
    def method1 
     var1 = [] 
     var2 = [] 
    #Do something with var1 and var2 
     print var1 
     print var2 
     return var1,var2 

sample = class1() 
sample.method1 

這裏是2類

from class1 import * 

class number2: 
    sample.method1() 

這並不如預期,並打印VAR1和VAR2,但我不能把內部類數VAR1或VAR2 2

修正編輯: 因爲任何人有這個問題,我通過導入這個上面的第二類固定它

from Module1 import Class1,sample 

然後裏面的Class2

 var1,var2 = smaple.method1() 
+0

這是你嘗試的確切代碼嗎? – vmonteco

+1

當然不是。它充滿了語法錯誤:缺少':',縮進,'類'關鍵字... – Francesco

回答

0

您發佈的代碼是完全在他的註釋語法錯誤,弗朗切斯科·賽義德的。也許你可以粘貼正確的。

您不會從類中導入,而是從包或模塊中導入。另外,除非是callable,否則不要「調用」變量。

你的情況,你可以只是有:

file1.py:

class class1: 
    def __init__(self): # In your class's code, self is the current instance (= this for othe languages, it's always the first parameter.) 
     self.var = 0 

    def method1(self): 
     print(self.var) 

sample = class1() 

file2.py:

from file1 import class1, sample 

class class2(class1): 
    def method2(self): 
     self.var += 1 
     print(self.var) 

v = class2()   # create an instance of class2 that inherits from class1 
v.method1()   # calls method inherited from class1 that prints the var instance variable 
sample.method1()  # same 
print(v.var)   # You can also access it from outside the class definition. 
v.var += 2   # You also can modify it. 
print(v.var) 
v.method2()   # Increment the variable, then print it. 
v.method2()   # same. 
sample.method1()  # Print var from sample. 
#sample.method2() <--- not possible because sample is an instance of class1 and not of class2 

注意,有method1()class2class2必須從class1繼承。但是你仍然可以從其他軟件包/模塊導入變量。

還要注意,var對於該類的每個實例都是唯一的。

+0

感謝您的評論,但我如何訪問var1和var2從這個 – javasaucebiner

+0

@javasaucebiner像一個正常的函數unles你想這個變量是相關的到實例或類。也許你可以更精確地知道你想要什麼。你真的嘗試了什麼,它怎麼沒有工作? – vmonteco

+0

我想繪製一個matplotlib圖,使用在class1中創建的var1和var2列表 – javasaucebiner

相關問題