의 핵심 개념 중 하나 객체 지향 프로그래밍 (OOP) 언어는 상속입니다. 이는 다른 클래스에서 클래스를 파생시켜 속성 및 메서드 집합을 공유하는 클래스 계층 구조를 만들 수 있는 메커니즘입니다. 상속은 한 클래스가 다른 클래스의 속성을 파생하거나 상속하는 기능입니다.
상속의 이점은 다음과 같습니다.
상속을 사용하면 클래스(즉, 기본 클래스)의 속성을 다른 클래스(즉, 파생 클래스)로 상속할 수 있습니다. Python 상속의 장점은 다음과 같습니다.
- 현실 세계의 관계를 잘 표현하고 있습니다.
- 그것은 제공합니다 재사용 성 코드. 우리는 동일한 코드를 반복해서 작성할 필요가 없습니다. 또한 클래스를 수정하지 않고도 클래스에 더 많은 기능을 추가할 수 있습니다.
- 이는 본질적으로 전이적입니다. 즉, 클래스 B가 다른 클래스 A에서 상속되면 B의 모든 하위 클래스가 자동으로 클래스 A에서 상속됩니다.
- 상속은 간단하고 이해하기 쉬운 모델 구조를 제공합니다.
- 상속으로 인해 개발 및 유지 관리 비용이 줄어듭니다.
Python 상속 구문
Python의 단순 상속 구문은 다음과 같습니다.
Class BaseClass: {Body} Class DerivedClass(BaseClass): {Body}> 부모 클래스 만들기
상위 클래스는 하위 클래스가 속성을 상속받는 클래스입니다. 라는 상위 클래스를 만들어 보겠습니다. 사람 이는 표시하다 그 사람의 정보를 표시하는 방법.
파이썬3
# A Python program to demonstrate inheritance> class> Person(>object>):> > ># 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>)> # Driver code> emp>=> Person(>'Satyam'>,>102>)># An Object of Person> emp.Display()> |
>
>
산출:
Satyam 102>
하위 클래스 만들기
하위 클래스는 상위 클래스의 속성을 구동하는 클래스입니다. 여기 엠프 의 속성을 상속받을 또 다른 클래스입니다. 사람 클래스(기본 클래스).
파이썬3
json 형식의 예
class> Emp(Person):> > >def> Print>(>self>):> >print>(>'Emp class called'>)> > Emp_details>=> Emp(>'Mayank'>,>103>)> # calling parent class function> Emp_details.Display()> # Calling child class function> Emp_details.>Print>()> |
>
>
산출:
Mayank 103 Emp class called>
Python의 상속 예
하위 클래스가 상위 클래스의 속성을 상속하는 간단한 Python 상속의 예를 살펴보겠습니다. 이 예에서 'Person'은 상위 클래스이고 'Employee'는 하위 클래스입니다.
파이썬3
numpy 고유
# A Python program to demonstrate inheritance> # Base or Super class. Note object in bracket.> # (Generally, object is made ancestor of all classes)> # In Python 3.x 'class Person' is> # equivalent to 'class Person(object)'> class> Person(>object>):> ># Constructor> >def> __init__(>self>, name):> >self>.name>=> name> ># To get name> >def> getName(>self>):> >return> self>.name> ># To check if this person is an employee> >def> isEmployee(>self>):> >return> False> # Inherited or Subclass (Note Person in bracket)> class> Employee(Person):> ># Here we return true> >def> isEmployee(>self>):> >return> True> # Driver code> emp>=> Person(>'Geek1'>)># An Object of Person> print>(emp.getName(), emp.isEmployee())> emp>=> Employee(>'Geek2'>)># An Object of Employee> print>(emp.getName(), emp.isEmployee())> |
>
>
산출:
Geek1 False Geek2 True>
Python의 객체 클래스란 무엇입니까?
처럼 자바 객체 클래스 , Python(버전 3.x부터)에서 객체는 모든 클래스의 루트입니다.
- Python 3.x에서는 Test(객체) 클래스와 Test 클래스가 동일합니다.
- Python 2.x에서 Test(object) 클래스는 객체를 부모로 사용하는 클래스(새 스타일 클래스라고 함)를 생성하고, Test 클래스는 객체를 생성하는 부모 없이 이전 스타일 클래스를 생성합니다.
서브클래싱(부모 클래스의 생성자 호출)
하위 클래스는 어느 클래스가 상위 클래스인지 식별해야 합니다. 이는 하위 클래스 정의에 상위 클래스 이름을 언급하여 수행할 수 있습니다.
예: 클래스 서브클래스_이름(슈퍼클래스_이름)
이 예에서는 'ㅏ' Person 클래스에 대해 생성된 인스턴스입니다. 참조된 클래스의 __init__()를 호출합니다. Person 클래스의 선언 부분에 'object'라고 쓰여 있는 것을 볼 수 있습니다. Python에서 모든 클래스는 '객체'라는 내장 기본 클래스에서 상속됩니다. 생성자, 즉 클래스의 '__init__' 함수는 객체 변수나 클래스의 인스턴스를 생성할 때 호출됩니다.
__init__() 내에 정의된 변수를 인스턴스 변수 또는 객체라고 합니다. 따라서 'name'과 'idnumber'는 Person 클래스의 객체입니다. 마찬가지로 'salary'와 'post'는 Employee 클래스의 객체입니다. Employee 클래스는 Person 클래스에서 상속되므로 'name'과 'idnumber'도 Employee 클래스의 객체입니다.
파이썬3
# Python code to demonstrate how parent constructors> # are called.> # parent class> class> Person(>object>):> ># __init__ is known as the constructor> >def> __init__(>self>, name, idnumber):> >self>.name>=> name> >self>.idnumber>=> idnumber> >def> display(>self>):> >print>(>self>.name)> >print>(>self>.idnumber)> # child class> class> Employee(Person):> >def> __init__(>self>, name, idnumber, salary, post):> >self>.salary>=> salary> >self>.post>=> post> ># invoking the __init__ of the parent class> >Person.__init__(>self>, name, idnumber)> # creation of an object variable or an instance> a>=> Employee(>'Rahul'>,>886012>,>200000>,>'Intern'>)> # calling a function of the class Person using its instance> a.display()> |
>
>
산출:
Rahul 886012>
부모의 __init__() 호출을 잊어버린 경우 오류를 보여주는 Python 프로그램
상위 클래스의 __init__() 호출을 잊어버리면 해당 인스턴스 변수를 하위 클래스에서 사용할 수 없습니다. 다음 코드는 같은 이유로 오류를 생성합니다.
파이썬3
class> A:> >def> __init__(>self>, n>=>'Rahul'>):> >self>.name>=> n> class> B(A):> >def> __init__(>self>, roll):> >self>.roll>=> roll> object> => B(>23>)> print>(>object>.name)> |
>
GB 대 MB
>
출력 :
Traceback (most recent call last): File '/home/de4570cca20263ac2c4149f435dba22c.py', line 12, in print (object.name) AttributeError: 'B' object has no attribute 'name'>
super() 함수
그만큼 슈퍼() 함수 상위 클래스를 나타내는 객체를 반환하는 내장 함수입니다. 하위 클래스에서 상위 클래스의 메소드 및 속성에 액세스할 수 있습니다.
예: 간단한 Python 상속을 사용하는 super() 함수
이 예에서는 하위 클래스의 'obj' 객체를 생성했습니다. 하위 클래스 'Student'의 생성자를 호출하면 객체 생성 중에 전달된 값으로 데이터 멤버가 초기화됩니다. 그런 다음 super() 함수를 사용하여 상위 클래스의 생성자를 호출했습니다.
파이썬3
# parent class> class> Person():> >def> __init__(>self>, name, age):> >self>.name>=> name> >self>.age>=> age> >def> display(>self>):> >print>(>self>.name,>self>.age)> # child class> class> Student(Person):> >def> __init__(>self>, name, age):> >self>.sName>=> name> >self>.sAge>=> age> ># inheriting the properties of parent class> >super>().__init__(>'Rahul'>, age)> >def> displayInfo(>self>):> >print>(>self>.sName,>self>.sAge)> obj>=> Student(>'Mayank'>,>23>)> obj.display()> obj.displayInfo()> |
>
>
산출:
Rahul 23 Mayank 23>
속성 추가
상속이 제공하는 기능 중 하나는 상위 클래스의 속성을 상속하고 하위 클래스에 새로운 속성을 추가하는 것입니다. 예를 들어 이를 살펴보겠습니다.
파이썬3
# parent class> class> Person():> >def> __init__(>self>, name, age):> >self>.name>=> name> >self>.age>=> age> >def> display(>self>):> >print>(>self>.name,>self>.age)> # child class> class> Student(Person):> >def> __init__(>self>, name, age, dob):> >self>.sName>=> name> >self>.sAge>=> age> >self>.dob>=> dob> ># inheriting the properties of parent class> >super>().__init__(>'Rahul'>, age)> >def> displayInfo(>self>):> >print>(>self>.sName,>self>.sAge,>self>.dob)> obj>=> Student(>'Mayank'>,>23>,>'16-03-2000'>)> obj.display()> obj.displayInfo()> |
>
>
산출:
여기서 우리는 자식 클래스에 생년월일(dob)이라는 새로운 속성을 추가한 것을 볼 수 있습니다.
Rahul 23 Mayank 23 16-03-2000>
다양한 유형의 Python 상속
Python에는 5가지 유형의 상속이 있습니다. 그것들은 다음과 같습니다:
- 단일 상속 : 자식 클래스가 하나의 부모 클래스로부터만 상속받는 경우를 단일 상속이라고 합니다. 우리는 위의 예를 보았습니다. 다중 상속 : 자식 클래스가 여러 부모 클래스로부터 상속을 받는 경우 이를 다중 상속이라고 합니다.
Java와 달리 Python은 다중 상속을 보여줍니다.
파이썬3
라이브 크리켓을 위한 mylivecricket
# Python example to show the working of multiple> # inheritance> class> Base1(>object>):> >def> __init__(>self>):> >self>.str1>=> 'Geek1'> >print>(>'Base1'>)> class> Base2(>object>):> >def> __init__(>self>):> >self>.str2>=> 'Geek2'> >print>(>'Base2'>)> class> Derived(Base1, Base2):> >def> __init__(>self>):> ># Calling constructors of Base1> ># and Base2 classes> >Base1.__init__(>self>)> >Base2.__init__(>self>)> >print>(>'Derived'>)> >def> printStrs(>self>):> >print>(>self>.str1,>self>.str2)> ob>=> Derived()> ob.printStrs()> |
>
>
산출:
Base1 Base2 Derived Geek1 Geek2>
- 다단계 상속 : 자녀와 손자 관계가 있을 때. 즉, 하위 클래스는 상위 클래스로부터 상속받고, 상위 클래스는 상위 클래스로부터 상속됩니다.
파이썬3
# A Python program to demonstrate inheritance> # Base or Super class. Note object in bracket.> # (Generally, object is made ancestor of all classes)> # In Python 3.x 'class Person' is> # equivalent to 'class Person(object)'> class> Base(>object>):> ># Constructor> >def> __init__(>self>, name):> >self>.name>=> name> ># To get name> >def> getName(>self>):> >return> self>.name> # Inherited or Sub class (Note Person in bracket)> class> Child(Base):> ># Constructor> >def> __init__(>self>, name, age):> >Base.__init__(>self>, name)> >self>.age>=> age> ># To get name> >def> getAge(>self>):> >return> self>.age> # Inherited or Sub class (Note Person in bracket)> class> GrandChild(Child):> ># Constructor> >def> __init__(>self>, name, age, address):> >Child.__init__(>self>, name, age)> >self>.address>=> address> ># To get address> >def> getAddress(>self>):> >return> self>.address> # Driver code> g>=> GrandChild(>'Geek1'>,>23>,>'Noida'>)> print>(g.getName(), g.getAge(), g.getAddress())> |
>
>
산출:
Geek1 23 Noida>
- 계층적 상속 단일 기반에서 둘 이상의 파생 클래스를 만들 수 있습니다. 하이브리드 상속: 이 형식은 두 가지 이상의 상속 형식을 결합합니다. 기본적으로 이는 여러 유형의 상속이 혼합된 것입니다.
자세한 내용은 다음 문서를 읽어보세요. Python의 상속 유형
상위 클래스의 비공개 멤버
우리는 항상 부모 클래스의 인스턴스 변수가 자식 클래스에 상속되는 것을 원하지 않습니다. 즉, 부모 클래스의 인스턴스 변수 중 일부를 자식 클래스에서 사용할 수 없는 비공개로 만들 수 있습니다.
Python 상속에서는 이름 앞에 이중 밑줄을 추가하여 인스턴스 변수를 비공개로 만들 수 있습니다. 예를 들어:
파이썬3
# Python program to demonstrate private members> # of the parent class> class> C(>object>):> >def> __init__(>self>):> >self>.c>=> 21> ># d is private instance variable> >self>.__d>=> 42> class> D(C):> >def> __init__(>self>):> >self>.e>=> 84> >C.__init__(>self>)> object1>=> D()> # produces an error as d is private instance variable> print>(object1.c)> print>(object1.__d)> |
>
CSS를 사용하여 밑줄
>
출력 :
여기서 변수 'c'를 인쇄하려고 하면 해당 값 21이 콘솔에 인쇄되는 것을 볼 수 있습니다. 반면 'd'를 인쇄하려고 하면 오류가 발생했습니다. 밑줄을 사용하여 변수 'd'를 비공개로 설정했기 때문입니다. 하위 클래스 'D'에서는 사용할 수 없으므로 오류가 발생합니다.
21 File '/home/993bb61c3e76cda5bb67bd9ea05956a1.py', line 16, in print (object1.d) AttributeError: type object 'D' has no attribute 'd'>