2017-02-12 89 views
0

我想使用在類B中的類A中定義的變量。基本上我需要類A中的用戶條目是我保存的數據的文件名在B類下面是我的代碼:在類A中使用變量在Python中的類B

class A(object): 

    def __init__(self, master): 
     self.master = master 
     self.labelSub=Label(self.master, text="Participant No.") #where users their name 
     self.entrySub=Entry(self.master,bg="grey") 
     A.csv_name_sub = str(self.entrySub.get()) #save users entry 

class B(A): 

    def __init__(self, master): 
     self.master = master 
     A.csv_name_sub = str(self.entrySub.get()) 
     self.resultFile = open("/Users/Desktop/" + A.csv_name_sub + 
          '_results.csv', 'w') #use the users entry as the name of the csv file I save 

但錯誤告訴我:「AttributeError錯誤:‘B’對象有沒有屬性‘entrySub’」。你能幫我解決嗎?謝謝!!

+0

通過在變量的類的開頭添加'Global'使其成爲一個全局變量。像'全球A' –

回答

0

繼承類A的構造函數沒有自動調用:https://docs.python.org/3.5/reference/datamodel.html?highlight=baseclass#object.init

callling基類的構造後,你的B的情況下應具備的屬性:

class B(A): 

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

https://docs.python.org/3.5/tutorial/classes.html#class-and-instance-variables解釋之間的區別類變量和實例變量。

編輯:Eric編輯得更快。 ;)

+0

嗨邁克爾,謝謝你的回覆。我試過你的代碼,沒有錯誤提示(程序運行),但文件名不會保存在'csv_name_sub + _results.csv'中。這裏是我的代碼'class B(A):def __init __(self,master):''A .__ init __(self,master)','A.csv_name_sub = str(self.entrySub.get())'''self。 resultFile = open(「/ Users/Desktop /」+ A.csv_name_sub +'_results.csv','w')'。它沒有說csv_name_sub不存在,但只是沒有顯示在文件名中。你知道爲什麼嗎? Thx再次! – key

2

Inside B.__init__A.__init__尚未被調用,所以self.entrySub尚未定義。

thread (Understanding Python super with init methods)可能會幫助你。

您可以用super的電話替換B.__init__的前兩行。

注意:你確定要混合類和實例變量嗎?所有A對象只有一個A.csv_name_sub,但它似乎取決於master,對於每個A對象可能都不相同。

+0

嗨,Eric,謝謝!在A類和B類上還有其他對象,因爲我想保持我的代碼簡潔,所以我沒有顯示它們。他們都是同一個主人。 – key

+0

我在你建議的頁面中使用了'class ChildA'' Base .__ init __(self)''(以下也是Michael建議的)。但它沒有正常工作。 AttributeError沒有出現,並且程序運行,但文件名不會根據條目而改變。這裏是我的代碼'class B(A):def __init __(self,master):''A .__ init __(self,master)','A.csv_name_sub = str(self.entrySub.get())'''self。 resultFile = open(「/ Users/Desktop /」+ A.csv_name_sub +'_results.csv','w')'。我得到的文件名只是「_results.csv」。你知道爲什麼嗎? – key

相關問題