파이썬 슈퍼()
Python에서는 super() 함수를 사용하여 상위 클래스나 슈퍼클래스를 참조합니다. 이를 통해 하위 클래스에서 상위 클래스에 정의된 메서드를 호출할 수 있으므로 상위 클래스에서 상속된 기능을 확장하고 사용자 정의할 수 있습니다.
Python의 super() 구문
통사론: 감독자()
반품 : 부모 클래스를 나타내는 프록시 객체를 반환합니다.
Python 예제의 super() 함수
주어진 예에서, 엠프 수업에는 __더운__ 초기화하는 메서드 ID , 그리고 이름 그리고 추가 속성. 그만큼 프리랜서 클래스는 다음에서 상속됩니다. 엠프 클래스를 추가하고 다음과 같은 추가 속성을 추가합니다. 이메일. 상속된 속성을 초기화하기 위해 부모 클래스의 __init__ 메서드 super()를 호출합니다.
파이썬3
class> Emp():> > def> __init__(> self> ,> id> , name, Add):> > self> .> id> => id> > self> .name> => name> > self> .Add> => Add> # Class freelancer inherits EMP> class> Freelance(Emp):> > def> __init__(> self> ,> id> , name, Add, Emails):> > super> ().__init__(> id> , name, Add)> > self> .Emails> => Emails> Emp_1> => Freelance(> 103> ,> 'Suraj kr gupta'> ,> 'Noida'> ,> 'KKK@gmails'> )> print> (> 'The ID is:'> , Emp_1.> id> )> print> (> 'The Name is:'> , Emp_1.name)> print> (> 'The Address is:'> , Emp_1.Add)> print> (> 'The Emails is:'> , Emp_1.Emails)> |
출력 :
The ID is: 103 The Name is: Suraj kr gupta The Address is: Noida The Emails is: KKK@gmails
super() 메소드는 어디에 사용되나요?
Python에서는 super() 함수를 사용하여 상위 클래스의 메서드를 호출할 수 있습니다. 이는 전형적인 관행이다. 객체 지향 프로그래밍 슈퍼클래스의 메서드를 호출하고 메서드 재정의 및 상속을 활성화합니다. 현재 클래스가 해당 메서드를 자체 구현으로 대체한 경우에도 super()를 호출하면 부모 클래스의 메서드에 액세스하고 사용할 수 있습니다. 이렇게 하면 부모 클래스의 동작을 향상하고 수정하는 동시에 이점을 얻을 수 있습니다.
슈퍼 기능의 장점
- 해당 메소드에 액세스하기 위해 상위 클래스 이름을 기억하거나 지정할 필요가 없습니다. 이 함수는 단일 상속과 다중 상속 모두에서 사용할 수 있습니다.
- 이는 전체 함수를 다시 작성할 필요가 없으므로 모듈성(변경 사항 격리)과 코드 재사용성을 구현합니다.
- Python의 super 함수는 Python이 다른 언어와 달리 동적 언어이기 때문에 동적으로 호출됩니다.
Python super 없이 상속은 어떻게 작동합니까?
주어진 예에는 Emp 클래스의 __init__ 메서드에 문제가 있습니다. Emp 클래스는 Person 클래스에서 상속되지만 해당 __init__ 메서드에서는 name 및 id 특성을 초기화하기 위해 부모 클래스의 __init__ 메서드를 호출하지 않습니다.
파이썬3
# code> class> Person:> > # Constructor> > def> __init__(> self> , name,> id> ):> > self> .name> => name> > self> .> id> => id> > # To check if this person is an employee> > def> Display(> self> ):> > print> (> self> .name,> self> .> id> )> > class> Emp(Person):> > > def> __init__(> self> , name,> id> ):> > self> .name_> => name> > def> Print> (> self> ):> > print> (> 'Emp class called'> )> Emp_details> => Emp(> 'Mayank'> ,> 103> )> # calling parent class function> Emp_details.name_, Emp_details.name> |
출력 :
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in 24 25 # calling parent class function --->26 Emp_details.name_, Emp_details.name AttributeError: 'Emp' 개체에 'name'>'> 속성이 없습니다.Python의 Super를 사용하여 위 문제 해결
제공된 코드에서 Emp 클래스는 Person 클래스에서 올바르게 상속되고 Emp 클래스의 __init__ 메서드는 이제 Python에서 super()를 사용하여 부모 클래스의 __init__ 메서드를 올바르게 호출합니다.
파이썬3
# code> # A Python program to demonstrate inheritance> class> Person:> > # Constructor> > def> __init__(> self> , name,> id> ):> > self> .name> => name> > self> .> id> => id> > # To check if this person is an employee> > def> Display(> self> ):> > print> (> self> .name,> self> .> id> )> > class> Emp(Person):> > > def> __init__(> self> , name,> id> ):> > self> .name_> => name> > super> ().__init__(name,> id> )> > def> Print> (> self> ):> > print> (> 'Emp class called'> )> Emp_details> => Emp(> 'Mayank'> ,> 103> )> # calling parent class function> print> (Emp_details.name_, Emp_details.name)> |
출력 :
Mayank Mayank
__init__() 메서드를 사용하여 Python super() 이해하기
Python에는 __init__이라는 예약된 메서드가 있습니다. 객체 지향 프로그래밍에서는 생성자라고 합니다. 이 메소드가 호출되면 클래스가 클래스의 속성을 초기화할 수 있습니다. 상속된 하위 클래스에서는 super() 함수를 사용하여 상위 클래스를 참조할 수 있습니다. super 함수는 하위 클래스에 대한 모든 메소드에 대한 액세스를 허용하는 슈퍼클래스의 임시 객체를 반환합니다.
메모: 자세한 내용은 다음을 참조하세요. Python의 상속 .
단일 상속을 사용한 슈퍼 함수
동물의 예를 들어보자. 개, 고양이, 소도 동물의 일부입니다. 그들은 또한 다음과 같은 공통된 특성을 공유합니다.
- 그들은 포유류입니다.
- 그들은 꼬리와 네 개의 다리를 가지고 있습니다.
- 그들은 가축입니다.
따라서 개, 고양이, 말 클래스는 동물 클래스의 하위 클래스입니다. 많은 하위 클래스가 단일 부모 클래스에서 상속되기 때문에 이는 단일 상속의 예입니다.
파이썬3
# Python program to demonstrate> # super function> class> Animals:> > # Initializing constructor> > def> __init__(> self> ):> > self> .legs> => 4> > self> .domestic> => True> > self> .tail> => True> > self> .mammals> => True> > def> isMammal(> self> ):> > if> self> .mammals:> > print> (> 'It is a mammal.'> )> > def> isDomestic(> self> ):> > if> self> .domestic:> > print> (> 'It is a domestic animal.'> )> class> Dogs(Animals):> > def> __init__(> self> ):> > super> ().__init__()> > def> isMammal(> self> ):> > super> ().isMammal()> class> Horses(Animals):> > def> __init__(> self> ):> > super> ().__init__()> > def> hasTailandLegs(> self> ):> > if> self> .tail> and> self> .legs> => => 4> :> > print> (> 'Has legs and tail'> )> # Driver code> Tom> => Dogs()> Tom.isMammal()> Bruno> => Horses()> Bruno.hasTailandLegs()> |
출력 :
It is a mammal. Has legs and tail
다중 상속이 있는 슈퍼
다른 것도 하자 슈퍼 함수의 예 , 수업을 가정 해 봅시다 날수있다 그리고 수영을 할 수 있다 포유류 클래스에서 상속되며 이러한 클래스는 동물 클래스에서 상속됩니다. 따라서 동물 클래스는 여러 기본 클래스에서 상속됩니다. 의 용도를 살펴보자 파이썬 인수가 매우 많음 이 경우.
파이썬3
class> Mammal():> > def> __init__(> self> , name):> > print> (name,> 'Is a mammal'> )> class> canFly(Mammal):> > def> __init__(> self> , canFly_name):> > print> (canFly_name,> 'cannot fly'> )> > # Calling Parent class> > # Constructor> > super> ().__init__(canFly_name)> class> canSwim(Mammal):> > def> __init__(> self> , canSwim_name):> > print> (canSwim_name,> 'cannot swim'> )> > super> ().__init__(canSwim_name)> class> Animal(canFly, canSwim):> > def> __init__(> self> , name):> > super> ().__init__(name)> # Driver Code> Carol> => Animal(> 'Dog'> )> |
출력 :
Animal 클래스는 두 부모 클래스(canFly 및 canSwim)에서 상속됩니다. 따라서 하위 클래스 인스턴스 Carol은 두 상위 클래스 생성자 모두에 액세스할 수 있습니다.
Dog cannot fly Dog cannot swim Dog Is a mammal
다단계 상속이 있는 슈퍼
다른 것도 하자 슈퍼 함수의 예 , can swim 클래스가 포유류 클래스의 canFly, canFly에 의해 상속되었다고 가정합니다. 따라서 포유류 클래스는 다중 수준 상속을 상속받습니다. 의 용도를 살펴보자 파이썬 인수가 매우 많음 이 경우.
파이썬3
class> Mammal():> > def> __init__(> self> , name):> > print> (name,> 'Is a mammal'> )> class> canFly(Mammal):> > def> __init__(> self> , canFly_name):> > print> (canFly_name,> 'cannot fly'> )> > # Calling Parent class> > # Constructor> > super> ().__init__(canFly_name)> class> canSwim(canFly):> > def> __init__(> self> , canSwim_name):> > print> (canSwim_name,> 'cannot swim'> )> > super> ().__init__(canSwim_name)> class> Animal(canSwim):> > def> __init__(> self> , name):> > # Calling the constructor> > # of both the parent> > # class in the order of> > # their inheritance> > super> ().__init__(name)> # Driver Code> Carol> => Animal(> 'Dog'> )> |
출력 :
Dog cannot swim Dog cannot fly Dog Is a mammal
Python 다중 상속 및 MRO
주어진 예제에서 클래스 C는 클래스 A와 B에서 상속되며 age() 메서드를 재정의합니다. 그러나 클래스 C의 age() 메서드에서 super(C, self).age() 줄은 MRO의 다음 클래스에서 age() 메서드를 호출합니다. 이 경우 MRO에서 클래스 B 앞에 나타나기 때문에 클래스 A의 age() 메서드를 호출합니다.
파이썬3
class> A:> > def> age(> self> ):> > print> (> 'Age is 21'> )> class> B:> > def> age(> self> ):> > print> (> 'Age is 23'> )> class> C(A, B):> > def> age(> self> ):> > super> (C,> self> ).age()> > c> => C()> print> (C.__mro__)> print> (C.mro())> |
출력 :
(, , , ) [, , , ]