我尝试使用class A
方法在class B
__init__()
中使用变量。但不知怎的,class A
和B中的变量无法显示(我的cvs写文件没有变化)。这是我的代码:
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_sub
和csv_name_ses
为空。
答案 0 :(得分: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 :(得分: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