Calling a class function inside of __init__

前端 未结 6 1863
夕颜
夕颜 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:36

    You must declare parse_file like this; def parse_file(self). The "self" parameter is a hidden parameter in most languages, but not in python. You must add it to the definition of all that methods that belong to a class. Then you can call the function from any method inside the class using self.parse_file

    your final program is going to look 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
    

提交回复
热议问题