사자자리
10장 객체와 클래스 본문
객체
속성(attribute) | 변수 | car.color, car.model, car.speed |
동작(action) | 메서드 | car.drive() |
클래스 정의와 객체 생성
class Car:
def drive(self):
self.speed = 10
#클래스로부터 객체 생성
mine = Car()
#생성된 객체 mine에 속성 추가
mine.color = "blue"
mine.model = "e-class"
#매서드 호출
mine.drive()
print(mine.color, mine.model, mine.speed)
<실행 결과>
blue e-class 10
클래스의 특별한 메서드
__init__() | 객체가 생성될 때, 속성을 초기화 |
__str__() | 객체를 print()로 출력할 때 자동으로 호출됨 |
class Car:
def __init__(self, color, model, speed):
self.color = color
self.model = model
self.speed = speed
def __str__(self):
msg = "색상: " + str(self.color) + " 모델: " + str(self.model) + " 속도: " + str(self.speed)
return msg
def drive(self):
self.speed = 50
sirius = Car("red", "ghost", 30)
regulus = Car("black", "phantom", 10)
sirius.drive()
print(sirius)
print(regulus)
<실행 결과>
색상: red 모델: ghost 속도: 50
색상: black 모델: phantom 속도: 10
상속
- 클래스를 정의할 때 부모 클래스를 지정하는 것
- 자식 클래스는 부모 클래스의 메서드와 변수들을 사용할 수 있다.
class Car:
def __init__(self, color, model, speed):
self.color = color
self.model = model
self.speed = speed
def __str__(self):
msg = "색상: " + str(self.color) + " 모델: " + str(self.model) + " 속도: " + str(self.speed)
return msg
def drive(self):
self.speed = 50
class PotterCar(Car): #상속
def fly(self):
self.fly = 'fly mode on'
James = PotterCar("red", "Cullinan", 30) #클래스 Car의 메서드를 사용할 수 있다.
James.drive()
James.fly()
print(James)
print("자동차의 모드: {}".format(James.fly))
<실행 결과>
색상: red 모델: Cullinan 속도: 50
자동차의 모드: fly mode on
'Python' 카테고리의 다른 글
11장 그래픽스 응용 (0) | 2022.06.13 |
---|---|
08장 GUI와 파일 처리 (0) | 2022.06.12 |
07장 함수 (0) | 2022.06.12 |
06장 리스트와 연산 (0) | 2022.06.12 |
Comments