IT박스

__init__ 내부에서 클래스 함수 호출

itboxs 2020. 8. 12. 07:58
반응형

__init__ 내부에서 클래스 함수 호출


파일 이름을 취하고 파일을 열고 일부 데이터를 구문 분석하는 코드를 작성 중입니다. 수업 시간에하고 싶습니다. 다음 코드가 작동합니다.

class MyClass():
    def __init__(self, filename):
        self.filename = filename 

        self.stat1 = None
        self.stat2 = None
        self.stat3 = None
        self.stat4 = None
        self.stat5 = None

        def parse_file():
            #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

        parse_file()

그러나 그것은 모든 파싱 기계 __init__를 내 클래스 함수 범위에 넣는 것과 관련이 있습니다. 이 단순화 된 코드에서는 이제 괜찮아 보이지만 함수 parse_file에는 몇 가지 수준의 들여 쓰기도 있습니다. 함수 parse_file()를 아래와 같은 클래스 함수로 정의하고 싶습니다.

class MyClass():
    def __init__(self, filename):
        self.filename = filename 

        self.stat1 = None
        self.stat2 = None
        self.stat3 = None
        self.stat4 = None
        self.stat5 = None
        parse_file()

    def parse_file():
        #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

물론이 코드는 함수 parse_file()함수 의 범위 내에 있지 않기 때문에 작동하지 않습니다 __init__. __init__해당 클래스 내에서 클래스 함수를 호출하는 방법이 있습니까? 아니면 잘못된 방식으로 생각하고 있습니까?


다음과 같이 함수를 호출하십시오.

self.parse_file()

You also need to define your parse_file() function like this:

def parse_file(self):

The parse_file method has to be bound to an object upon calling it (because it's not a static method). This is done by calling the function on an instance of the object, in your case the instance is self.


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()

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].


In parse_file, take the self argument (just like in __init__). If there's any other context you need then just pass it as additional arguments as usual.


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

I think that your problem is actually with not correctly indenting init function.It should be like this

class MyClass():
     def __init__(self, filename):
          pass

     def parse_file():
          pass

참고URL : https://stackoverflow.com/questions/12646326/calling-a-class-function-inside-of-init

반응형