Programming

파이썬에서 상속 및 __init__ 재정의

procodes 2020. 7. 11. 22:43
반응형

파이썬에서 상속 및 __init__ 재정의


나는 'Dive Into Python'을 읽고 수업 장에서 다음 예제를 제공합니다.

class FileInfo(UserDict):
    "store file metadata"
    def __init__(self, filename=None):
        UserDict.__init__(self)
        self["name"] = filename

그런 다음 작성자는 __init__메소드 를 대체 __init__하려면 올바른 매개 변수를 사용 하여 상위 명시 적으로 호출해야 한다고 말합니다 .

  1. 만약 그 FileInfo반에 조상 반이 둘 이상 있다면 어떨까요?
    • 모든 조상 클래스의 __init__메소드 를 명시 적으로 호출해야 합니까?
  2. 또한 재정의하려는 다른 방법 으로이 작업을 수행해야합니까?

이 책은 서브 클래스-수퍼 클래스 호출과 관련하여 약간 날짜가있다. 서브 클래스 내장 클래스와 관련하여 약간 날짜가 있습니다.

요즘 이렇게 생겼습니다.

class FileInfo(dict):
    """store file metadata"""
    def __init__(self, filename=None):
        super( FileInfo, self ).__init__()
        self["name"] = filename

다음 사항에 유의하십시오.

  1. 우리는 직접 내장 클래스와 같은 하위 클래스 dict, list, tuple, 등

  2. super함수는이 클래스의 수퍼 클래스를 추적하고 적절하게 함수를 호출하는 것을 처리합니다.


상속 해야하는 각 클래스에서 하위 클래스를 시작할 때 초기화 해야하는 각 클래스의 루프를 실행할 수 있습니다 ... 복사 가능한 예제가 더 잘 이해 될 수 있습니다 ...

class Female_Grandparent:
    def __init__(self):
        self.grandma_name = 'Grandma'

class Male_Grandparent:
    def __init__(self):
        self.grandpa_name = 'Grandpa'

class Parent(Female_Grandparent, Male_Grandparent):
    def __init__(self):
        Female_Grandparent.__init__(self)
        Male_Grandparent.__init__(self)

        self.parent_name = 'Parent Class'

class Child(Parent):
    def __init__(self):
        Parent.__init__(self)
#---------------------------------------------------------------------------------------#
        for cls in Parent.__bases__: # This block grabs the classes of the child
             cls.__init__(self)      # class (which is named 'Parent' in this case), 
                                     # and iterates through them, initiating each one.
                                     # The result is that each parent, of each child,
                                     # is automatically handled upon initiation of the 
                                     # dependent class. WOOT WOOT! :D
#---------------------------------------------------------------------------------------#



g = Female_Grandparent()
print g.grandma_name

p = Parent()
print p.grandma_name

child = Child()

print child.grandma_name

당신은 정말하지 않습니다 통화에 __init__기본 클래스 (들)의 방법을,하지만 당신은 일반적으로 원하는 기본 클래스 작업에 수업 방법의 나머지 부분에 대한 필요가 몇 가지 중요한 초기화를 할 것이기 때문에 그것을 할 수 있습니다.

For other methods it depends on your intentions. If you just want to add something to the base classes behavior you will want to call the base classes method additionally to your own code. If you want to fundamentally change the behavior, you might not call the base class' method and implement all the functionality directly in the derived class.


If the FileInfo class has more than one ancestor class then you should definitely call all of their __init__() functions. You should also do the same for the __del__() function, which is a destructor.


Yes, you must call __init__ for each parent class. The same goes for functions, if you are overriding a function that exists in both parents.

참고URL : https://stackoverflow.com/questions/753640/inheritance-and-overriding-init-in-python

반응형