>  기사  >  백엔드 개발  >  Python에서 super() 함수의 __init__() 메서드를 사용하는 방법은 무엇입니까?

Python에서 super() 함수의 __init__() 메서드를 사용하는 방법은 무엇입니까?

WBOY
WBOY앞으로
2023-04-27 10:13:131761검색

super().__ init__ () 용도는 무엇인가요?

super().__init__() 、 super(B,self).__init__()

1. super()와 __init__()를 각각 이해하세요

1.1, super()

Python에서 super() 함수의 __init__() 메서드를 사용하는 방법은 무엇입니까?

需要注意的是python2、3的super写法稍有不同。
1.2, __init__()

__init__()는 생성 시 "자동으로 호출됨"에서 Python의 생성자입니다. 객체.

Python에서 super() 함수의 __init__() 메서드를 사용하는 방법은 무엇입니까?

定义类时可以不写init方法,系统会默认创建,
你也可以写一个,让你的类在创建时完成一些“动作”。
1.3, super().__ init __()

하위 클래스 B와 상위 클래스 A가 모두 초기화 메서드를 작성한 경우
그러면 A의 초기화 메서드가 B로 덮어쓰여집니다. A의 init 메소드를 호출하려면 super를 사용하여 호출해야 합니다.

Python에서 super() 함수의 __init__() 메서드를 사용하는 방법은 무엇입니까?

물론 B 내에서는 super를 사용하여 부모 클래스의 메서드를 호출하는 것 외에도 부모 클래스 이름을 사용하여 호출할 수도 있습니다. 예:

class B(A):
    def __init__(self):
        A.__init__(self)
        print("B init")
1.3.1 "override"에 대한 질문 "

어떤 분들은 오해하실 수도 있어요" "커버링"은 "커버링"하면 그런게 없다는 뜻인데 왜 아직도 슈퍼를 통해 호출이 가능한 걸까요?
덮어쓴다고 해서 A의 메서드가 여전히 존재한다는 의미는 아니지만 B 내부에서 super를 호출해야 합니다.

例:
A里写了一个方法hi(), B继承自A, B里也写了一个方法hi()。
B的对象在外部调用hi(), 就只能调用B里面写的这个hi()。
想通过B调用A的hi(),只能在B内部用super().hi()调用。
class A:
    def hi(self):
        print("A hi")

class B(A):
    def hello(self):
        print("B hello")
        
b = B()
b.hi()       # B里没有写hi(),这里调用的是继承自A的hi()

------------------------------------------------------------------
class A:
    def hi(self):
        print("A hi")

class B(A):
    def hi(self):
        print("B hi")
        
b = B()
b.hi()    # 这里调用的就是B自己的hi()
------------------------------------------------------------------
class A:
    def hi(self):
        print("A hi")

class B(A):
    def hi(self):
        super().hi()         # 通过super调用父类A的hi()
        print("B hi")
        
b = B()
b.hi()    # 这里调用的就是B里面的hi()

2 python2와 3의 super() 차이점

Python3.x와 Python2.x의 차이점: Python 3에서는 super(Class, self).xxx 대신 super().xxx를 직접 사용할 수 있습니다.

예:

python3은 다음과 같이 직접 작성됩니다: super().__init__()
python2는 다음과 같이 작성되어야 합니다: super(class name, self).__init__()

Python3.x 예:

class A:
     def add(self, x):
         y = x+1
         print(y)
class B(A):
    def add(self, x):
        super().add(x)
b = B()
b.add(2)  # 3

Python2.x 예:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class A(object):   # Python2.x 记得继承 object
    def add(self, x):
         y = x+1
         print(y)
class B(A):
    def add(self, x):
        super(B, self).add(x)
b = B()
b.add(2)  # 3

3. 상속 순서에 관하여

최하위 레벨: 먼저 상위 클래스 A를 작성합니다

class A:
    def __init__(self):
        print('A')

두 번째 레벨: B, C, D가 A

class B(A):
    def __init__(self):
        print('B')
        super().__init__()

class C(A):
    def __init__(self):
        print('C')
        super().__init__()

class D(A):
    def __init__(self):
        print('D')
        super().__init__()
에서 상속받도록 합니다

세 번째 레벨: E, F와 G는 상속

class E(B, C):
    def __init__(self):
        print('E')
        super().__init__()

class F(C, D):
    def __init__(self):
        print('F')
        super().__init__()

class G(E, F):
    def __init__(self):
        print('G')
        super().__init__()

G의 상속 순서를 보면

Python에서 super() 함수의 __init__() 메서드를 사용하는 방법은 무엇입니까?

Python에서 super() 함수의 __init__() 메서드를 사용하는 방법은 무엇입니까?

G는 E에서 상속하고 F는 병렬임을 알 수 있습니다. 초기화 중에 F가 초기화되기 전에 E는 초기화되지 않습니다.

4. 여러 인스턴스의 super(python3) 비교

다음은 세 가지 상속 및 호출의 차이점을 비교하고 super().__init__()의 목적을 이해합니다.

4.1, 인스턴스

Python에서 super() 함수의 __init__() 메서드를 사용하는 방법은 무엇입니까?

하위 클래스 이름 상속된 콘텐츠 Puple은 모두 Puple_Init 상속되지만 재정의됩니다. 초기화 방법을 얻었습니다Puple_Super 상속하되 init 메서드를 재정의하고 init
을 상속합니다.
4.2에 super().__init__()를 추가하고 결과 및 비교

Python에서 super() 함수의 __init__() 메서드를 사용하는 방법은 무엇입니까?

4.3, 전체 코드

Python에서 super() 함수의 __init__() 메서드를 사용하는 방법은 무엇입니까?

위 내용은 Python에서 super() 함수의 __init__() 메서드를 사용하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제