상속
: 클래스끼리 물려주거나 물려받는 것
물려준 클래스(부모클래스,super)의 속성과 기능을
물려받는 클래스(자식클래스,sub)에서 사용이 가능하도록 만들고
추가적인 표현을 통하여 새로운 클래스를 만드는 문법
상속의 목적
클래스의 재사용(재활용)
프로그램의 유연성(추가, 수정, 삭제, etc.)을 증대 시키기위해서 사용
상속 시 주의 사항
1. 자식이더라도 부모의 private 멤버는 접근 불가
2. 자식클래스에서 부모클래스를 명시
형식
class 자식클래스명(부모클래스명) :
코드정의
class Bumo:
def disp(self):
print("내가 부모다!")
class JaSik(Bumo):
def info(self):
print("내가 자식이다!")
j = JaSik()
j.disp()
j.info()
자식클래스 생성
자식클래스 객체가 생성될 때 자동으로 부모클래스의 생성자가 호출된다
부모클래스의 멤버변수의 값을 초기화 하려면 자식클래스에서 함께 받아주어야 한다
부모클래스의 멤버변수값을 초기화하기 위해 부모클래스의 생성자를 함께 호출해주어야 한다
super : 부모, self : 자식
super : 부모의 인스턴스 공간을 컨트롤하는 클래스
class Info:
count = 0
def __init__(self,name = None,age = 0) -> None:
print("부모 생성자 호출")
Info.count+=1
self.__name = name
self.set_age(age)
#self.__age = age
#setter
def set_age(self,age):
if age < 1:
print("나이를 잘못 입력하셨습니다.")
self.__age = 1
return
self.__age = age
#getter
def get_age(self):
return self.__age
@property
def name(self):
return self.__name
@name.setter
def name(self,name:str):
if name.__len__() < 2:
print("이름은 두글자 이상입니다.")
return
self.__name = name
def setData(self,name,age):
self.__name = name
self.set_age(age)
def disp(self) -> None:
print("번호 : {}".format(Info.count))
print("이름 : {}".format(self.__name))
print("나이 : {}".format(self.__age))
@classmethod
def create(cls):
return Info()
# def __str__(self) -> str:
# return "이름 : {}".format(self.__name) + "\n나이 : {}".format(self.__age)
def __del__(self):
print("부모 소멸자 호출")
Info.count-=1
class NewInfo(Info):
def __init__(self, name=None, age=0, height=0.0) -> None:
super().__init__(name, age) # 제일위에 적는것을 권장한다...
print("자식 생성자 호출")
# self.__name = name
# self.__age = age
self.__height = height
def set_height(self,height):
self.__height = height
def get_height(self):
return self.__height
'''
메소드의 오버라이드
: 메소드의 재정의
코드의 일부분을 수정하려 할때 사용되는 구문
객체 상황상 맞지 않는 부분을 수정하여야 할 때 사용한
'''
def disp(self) -> None:
super().disp()
# print("번호 : {}".format(Info.count))
# print("이름 : {}".format(self.name))
# print("나이 : {}".format(self.get_age()))
print("키 : {}".format(self.__height))
a = NewInfo("김땡땡",20,177.4)
a.disp()
print(Info.count)
출력화면
별도의 폴더로 관리
다른 폴더 내부에 있는 클래스를 상속받기 위해서는
import로 부모클래스의 폴더를 불러온 후 (폴더명.부모클래스명) 형태로 불러옴
class Bumo:
def disp(self):
print("내가 부모다!")
import sys,os
print(os.path.dirname(os.path.abspath(os.path.dirname(__file__))) + "\\Bu")
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from Bu.Bumo import Bumo
class JaSik(Bumo):
def info(self):
print("내가 자식이다!")
j = JaSik()
j.disp()
출력화면
Exercise
기존에 Mobile이라는 클래스를 사용하여 휴대전화 정보를 관리했습니다.
세월이 지나서 항목들이 추가가 되었습니다.
Mobile이라는 클래스는 건드리지 않고
상속을 이용하여 추가된 항목까지 저장하게 만들고 싶습니다.
이름은 MobileEx로 생성
(추가된 항목) 제휴카드(card) 수시로 설정 / 확인 가능
약정기간(month) 휴대폰 약정기간(월)
(아래의 객체를 생성한 뒤 정보 출력)
name telecom price card month
[1] 아이폰7 KT 90만원 국민카드 24개월
[2] 갤럭시7 SK 30만원 신한카드 30개월
[3] G6 LG 35만원 삼성카드 36개월
<기존 프로그램>
class Mobile:
def __init__(self,name,tel = None,price = 400000) -> None:
self.__set_name(name)
self.__tel = tel
self.set_price(price)
def __set_name(self,name):
self.__name = name
def set_tel(self,tel):
self.__tel = tel
def set_price(self,price:int):
if price <= 400000:
self.__price = 400000
return
self.__price = price
def get_name(self):
return self.__name
def get_tel(self):
return self.__tel
def get_price(self):
return self.__price
def disp(self):
print("모델명 : {}".format(self.__name))
print("통신사 : {}".format(self.__tel))
print("가격 : {}원".format(self.__price))
def compare(self,m):
if self.__price < m.__price:
print(m.__name)
elif self.__price > m.__price:
print(self.__name)
else:
print("같다")
def __str__(self) -> str:
return "{}\t{}\t{}원".format(self.__name,self.__tel,self.__price)
@classmethod
def mobileList(cls,ls:list):
print("\tname\ttel\tprice")
if ls.__len__() == 0:
print("데이터가 없습니다.")
else:
for i in range(ls.__len__()):
#print("[{}]\t{}\t{}\t{}원".format(i + 1,ls[i].__name,ls[i].__tel,ls[i].__price))
print("[{}]\t{}".format(i + 1,ls[i]))
@classmethod
def compare(cls,m1,m2):
if m1.__price < m2.__price:
print(m2.__name)
elif m1.__price > m2.__price:
print(m1.__name)
else:
print("같다")
class MobileEx(Mobile):
def __init__(self, name, tel=None, price=400000, card=None, month=None) -> None:
super().__init__(name, tel, price)
self.__card = card
self.__month = month
def set_card(self, card):
self.__card = card
def get_card(self):
return self.__card
def set_month(self, month):
self.__month = month
def get_month(self):
return self.__month
def disp(self):
super().disp()
print("제휴카드 : {}".format(self.__card))
print("약정개월수 : {}개월".format(self.__month))
def __str__(self) -> str:
return "{}\t{}\t{}원\t{}\t{}개월".format(self.get_name(),self.get_tel(),self.get_price(),self.__card,self.__month)
@classmethod
def mobileList(cls,ls:list):
print("\tname\ttel\tprice\tcard\tmonth")
if ls.__len__() == 0:
print("데이터가 없습니다.")
else:
for i in range(ls.__len__()):
#print("[{}]\t{}\t{}\t{}원".format(i + 1,ls[i].__name,ls[i].__tel,ls[i].__price))
print("[{}]\t{}".format(i+1, ls[i]))
a = MobileEx("갤럭시23", "SKT", 1000000, "삼성카드", "36")
b = MobileEx("아이폰미니", "LG U+", 500000)
b.set_card("현대카드")
b.set_month("24")
a.disp()
b.disp()
MobileEx.mobileList([a,b])
출력화면
'Backend > Python' 카테고리의 다른 글
Python 파이썬 예외 처리 try except (0) | 2023.07.06 |
---|---|
Python 파이썬 상속 : 바인딩, 추상클래스, 다중상속, 상속 예제 풀이 (0) | 2023.07.05 |
Python 파이썬 생성자, 클래스 예제 03 (0) | 2023.07.04 |
Python 파이썬 생성자, 클래스 예제 02 (0) | 2023.07.04 |
Python 파이썬 생성자, 클래스 예제 01 (0) | 2023.07.04 |