2017-02-14 61 views
-2

在類B中使用變量我試圖通過使用__init__()方法在class A中使用class B中的變量。但不知何故class A和B中的變量無法顯示(我的CVS寫入文件沒有改變)。這裏是我的代碼:使用A .__ init __()方法

class Welcome(object): 

    csv_name_sub = None 
    csv_name_ses = None 

    def __init__(self, master, csv_name_sub = None, csv_name_ses = None): 
     self.entrySub=Entry(self.master,bg="grey") 
     self.entrySes=Entry(self.master,bg="grey") 

     self.csv_name_sub = str(self.entrySub.get()) 
     self.csv_name_ses = str(self.entrySes.get()) 

    def writeToFile(self): 
     with open("/Users/Desktop/" + self.csv_name_sub+ '_' + self.csv_name_ses + '_subjectNo.csv', 
       'w') as resultFile: 
     resultFileWrite=.... 

class App(Welcome): 

    def __init__(self, master): 
     Welcome.__init__(self, master) #I'm using python 3.5 

     Welcome.csv_name_sub = str(self.entrySub.get()) 
     Welcome.csv_name_ses = str(self.entrySes.get()) 

     print('session is', Welcome.csv_name_ses) 
     print("subject is", Welcome.csv_name_sub) 

     self.resultFile = open("/Users/Desktop/" + Welcome.csv_name_sub + '_' + Welcome.csv_name_ses + '_results.csv', 'w') 

該程序可以無錯運行,但csv_name_subcsv_name_ses是空的,當我在這兩類打印出來。

+1

In P ython,空白很重要。你可以檢查你的方法的格式/標籤? –

+0

Thans爲您提醒Rocket,只是改變了! – key

回答

2

更新的屬性綁定到實例而不是超類。從self

class App(Welcome): 

    def __init__(self, master): 
     Welcome.__init__(self, master) # Updated attributes are bound to self 

     self.csv_name_sub = str(self.entrySub.get()) 
     self.csv_name_ses = str(self.entrySes.get()) 
     ... 
1

使用實例的屬性,即:你應該使用self引用通過實例的屬性

class App(Welcome): 

    def __init__(self, master): 
     super().__init__(master) #I'm using python 3. 

     print('session is', self.csv_name_ses) 
     print("subject is", self.csv_name_sub) 

工作例如:

class Entry(object): 

    def __init__(self, master, bg): 
     pass 

    def get(self): 
     return 42 


class Welcome(object): 

    def __init__(self, master): 
     self.master = master 
     self.entrySub = Entry(self.master, bg="grey") 
     self.entrySes = Entry(self.master, bg="grey") 

     self.csv_name_sub = str(self.entrySub.get()) 
     self.csv_name_ses = str(self.entrySes.get()) 

class App(Welcome): 

    def __init__(self, master): 
     super().__init__(master) 

     print('session is', self.csv_name_ses) 
     print("subject is", self.csv_name_sub) 


app = App('x') 

輸出:

session is 42 
subject is 42 
+0

謝謝! Entry(歡迎課程)是一個tkinter入口小部件,這裏輸入的內容將在App類中打印。 'str(self.entrySub.get())'得到用戶的輸入。我試圖將你的代碼合併到我的。但仍然無法打印'self.csv_name_ses'。再次,程序運行正常,沒有錯誤。你有什麼想法,爲什麼?真的很感激它! – key

+0

也許'self.entrySub.get()'的結果返回一個空字符串。 –