Calling a class function inside of __init__

前端 未结 6 1844
夕颜
夕颜 2020-12-02 06:13

I\'m writing some code that takes a filename, opens the file, and parses out some data. I\'d like to do this in a class. The following code works:

class MyCl         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 06:35

    If I'm not wrong, both functions are part of your class, you should use it like this:

    class MyClass():
        def __init__(self, filename):
            self.filename = filename 
    
            self.stat1 = None
            self.stat2 = None
            self.stat3 = None
            self.stat4 = None
            self.stat5 = None
            self.parse_file()
    
        def parse_file(self):
            #do some parsing
            self.stat1 = result_from_parse1
            self.stat2 = result_from_parse2
            self.stat3 = result_from_parse3
            self.stat4 = result_from_parse4
            self.stat5 = result_from_parse5
    

    replace your line:

    parse_file() 
    

    with:

    self.parse_file()
    

提交回复
热议问题