使用A .__ init __()方法在B类的A类中使用变量

时间:2017-02-14 17:37:23

标签: python class variables init

我尝试使用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_subcsv_name_ses为空。

2 个答案:

答案 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