programing

python의 __init_ 상속 및 재정의

lastcode 2023. 9. 4. 20:08
반응형

python의 __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__기본 클래스의 메서드입니다. 그러나 기본 클래스는 나머지 클래스 메서드가 작동하는 데 필요한 몇 가지 중요한 초기화를 수행하기 때문에 일반적으로 이 작업을 수행합니다.

다른 방법의 경우에는 사용자의 의도에 따라 다릅니다.기본 클래스 동작에 무언가를 추가하려는 경우 자신의 코드에 추가로 기본 클래스 메서드를 호출할 수 있습니다.동작을 근본적으로 변경하려는 경우 기본 클래스의 메서드를 호출하지 않고 파생 클래스에서 모든 기능을 직접 구현할 수 있습니다.

FileInfo 클래스에 두 개 이상의 상위 클래스가 있는 경우 모든 상위 클래스를 호출해야 합니다.__init__()기능들.당신은 또한 그것에 대해 같은 것을 해야 합니다.__del__()함수, 즉 소멸자입니다.

예, 전화해야 합니다.__init__각 상위 클래스에 대해두 부모 모두에 존재하는 함수를 재정의하는 경우 함수도 마찬가지입니다.

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

반응형