# PohamHandle 클래스와 PohamCar 클래스 간의 포함 관계
class PohamHandle:
quantity = 0 # 회전량
def LeftTurn(self, q):
self.quantity = q
return '좌회전'
def RightTurn(self, q):
self.quantity = q
return '우회전'
def StraightTurn(self, q):
self.quantity = q
return '직진'
class PohamCar:
turnShow = '정지'
def __init__(self, ownerName):
self.ownerName = ownerName
self.handle = PohamHandle()
def TurnHandle(self, q):
if q > 0:
self.turnShow = self.handle.RightTurn(q)
elif q < 0:
self.turnShow = self.handle.LeftTurn(q)
elif q == 0:
self.turnShow = self.handle.StraightTurn(q)
# 객체 생성 및 메서드 호출
tom = PohamCar('tom')
tom.TurnHandle(20)
print(f"{tom.ownerName}의 회전량은 {tom.turnShow} {tom.handle.quantity}")
클래스 간 상속 (Is-a 관계)
상속은 자원의 재활용성을 높이고 코드의 중복을 줄이는 데 중요한 역할을 한다. 상속을 통해 부모 클래스의 기능을 자식 클래스에서 재사용하거나 확장할 수 있다.
class Animal:
eat = '음식'
def move(self):
print('움직이는 생물')
class Dog(Animal):
pass
class Horse(Animal):
pass
dog1 = Dog()
print(dog1.eat) # 음식
dog1.move() # 움직이는 생물
class Person:
say = '난 사람입니다.'
def __init__(self, nai):
print('Person 생성자 호출')
self.nai = nai
def Printinfo(self):
print(f"나이: {self.nai}, say: {self.say}")
class Employee(Person):
say = '말하는 동물'
def __init__(self):
print('Employee의 생성자')
def EprintInfo(self):
super().Printinfo()
print(f"업무: {self.say}")
e = Employee()
e.EprintInfo()
오버라이딩과 다중 상속
상속에서 자식 클래스는 부모 클래스의 메서드를 오버라이딩(재정의)할 수 있다. 또한, Python은 다중 상속을 지원하며, 이 경우 상속받는 순서가 중요하다.
class Parent:
def printData(self):
pass
class Child1(Parent):
def printData(self):
print('Child1의 printData 수행')
class Child2(Parent):
def printData(self):
print('Child2의 printData 수행')
c1 = Child1()
c1.printData() # Child1의 printData 수행
c2 = Child2()
c2.printData() # Child2의 printData 수행
class Tiger:
data = "호랑이 세상"
def Cry(self):
print('어흥')
class Lion:
def Cry(self):
print('으르렁')
def Hobby(self):
print('낮잠자기')
class Liger(Tiger, Lion):
pass
l1 = Liger()
print(l1.data) # 호랑이 세상
l1.Cry() # 어흥
l1.Hobby() # 낮잠자기