Calling a class function inside of __init__

前端 未结 6 1842
夕颜
夕颜 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条回答
  •  -上瘾入骨i
    2020-12-02 06:48

    How about:

    class MyClass(object):
        def __init__(self, filename):
            self.filename = filename 
            self.stats = parse_file(filename)
    
    def parse_file(filename):
        #do some parsing
        return results_from_parse
    

    By the way, if you have variables named stat1, stat2, etc., the situation is begging for a tuple: stats = (...).

    So let parse_file return a tuple, and store the tuple in self.stats.

    Then, for example, you can access what used to be called stat3 with self.stats[2].

提交回复
热议问题