728x90
8장 객체와 클래스¶
클래스 선언¶
객체 생성 및 활용¶
[8장: 137페이지]
In [1]:
class Bicycle(): # 클래스 선언
pass
[8장: 138페이지]
In [2]:
my_bicycle = Bicycle()
[8장: 138페이지]
In [3]:
my_bicycle
Out[3]:
<__main__.Bicycle at 0x1f2d0693cd0>
[8장: 138페이지]
In [4]:
my_bicycle.wheel_size = 26
my_bicycle.color = 'black'
[8장: 139페이지]
In [5]:
print("바퀴 크기:", my_bicycle.wheel_size) # 객체의 속성 출력
print("색상:", my_bicycle.color)
바퀴 크기: 26
색상: black
[8장: 139페이지]
In [6]:
class Bicycle():
def move(self, speed):
print("자전거: 시속 {0}킬로미터로 전진".format(speed))
def turn(self, direction):
print("자전거: {0}회전".format(direction))
def stop(self):
print("자전거({0}, {1}): 정지 ".format(self.wheel_size, self.color))
[8장: 140페이지]
In [7]:
my_bicycle = Bicycle() # Bicycle 클래스의 인스턴스인 my_bicycle 객체 생성
my_bicycle.wheel_size = 26 # 객체의 속성 설정
my_bicycle.color = 'black'
my_bicycle.move(30) # 객체의 메서드 호출
my_bicycle.turn('좌')
my_bicycle.stop()
자전거: 시속 30킬로미터로 전진
자전거: 좌회전
자전거(26, black): 정지
[8장: 141페이지]
In [8]:
bicycle1 = Bicycle() # Bicycle 클래스의 인스턴스인 bicycle1 객체 생성
bicycle1.wheel_size = 27 # 객체의 속성 설정
bicycle1.color = 'red'
bicycle1.move(20)
bicycle1.turn('좌')
bicycle1.stop()
자전거: 시속 20킬로미터로 전진
자전거: 좌회전
자전거(27, red): 정지
In [9]:
bicycle2 = Bicycle() # Bicycle 클래스의 인스턴스인 bicycle2 객체 생성
bicycle2.wheel_size = 24 # 객체의 속성 설정
bicycle2.color = 'blue'
bicycle2.move(15)
bicycle2.turn('우')
bicycle2.stop()
자전거: 시속 15킬로미터로 전진
자전거: 우회전
자전거(24, blue): 정지
객체 초기화¶
[8장: 142페이지]
In [10]:
class Bicycle():
def __init__(self, wheel_size, color):
self.wheel_size = wheel_size
self.color = color
def move(self, speed):
print("자전거: 시속 {0}킬로미터로 전진".format(speed))
def turn(self, direction):
print("자전거: {0}회전".format(direction))
def stop(self):
print("자전거({0}, {1}): 정지 ".format(self.wheel_size, self.color))
[8장: 142페이지]
In [11]:
my_bicycle = Bicycle(26, 'black') # 객체 생성과 동시에 속성값을 지정.
my_bicycle.move(30) # 객체 메서드 호출
my_bicycle.turn('좌')
my_bicycle.stop()
자전거: 시속 30킬로미터로 전진
자전거: 좌회전
자전거(26, black): 정지
8.2 클래스를 구성하는 변수와 함수¶
클래스에서 사용하는 변수¶
[8장: 143페이지]
In [12]:
class Car():
instance_count = 0 # 클래스 변수 생성 및 초기화
def __init__(self, size, color):
self.size = size # 인스턴스 변수 생성 및 초기화
self.color = color # 인스턴스 변수 생성 및 초기화
Car.instance_count = Car.instance_count + 1 # 클래스 변수 이용
print("자동차 객체의 수: {0}".format(Car.instance_count))
def move(self):
print("자동차({0} & {1})가 움직입니다.".format(self.size, self.color))
[8장: 144페이지]
In [13]:
car1 = Car('small', 'white')
car2 = Car('big', 'black')
자동차 객체의 수: 1
자동차 객체의 수: 2
[8장: 144페이지]
In [14]:
print("Car 클래스의 총 인스턴스 개수:{}".format(Car.instance_count))
Car 클래스의 총 인스턴스 개수:2
[8장: 144페이지]
In [15]:
print("Car 클래스의 총 인스턴스 개수:{}".format(car1.instance_count))
print("Car 클래스의 총 인스턴스 개수:{}".format(car2.instance_count))
Car 클래스의 총 인스턴스 개수:2
Car 클래스의 총 인스턴스 개수:2
[8장: 144페이지]
In [16]:
car1.move()
car2.move()
자동차(small & white)가 움직입니다.
자동차(big & black)가 움직입니다.
[8장: 145페이지]
In [17]:
class Car2():
count = 0; # 클래스 변수 생성 및 초기화
def __init__(self, size, num):
self.size = size # 인스턴스 변수 생성 및 초기화
self.count = num # 인스턴스 변수 생성 및 초기화
Car2.count = Car2.count + 1 # 클래스 변수 이용
print("자동차 객체의 수: Car2.count = {0}".format(Car2.count))
print("인스턴스 변수 초기화: self.count = {0}".format(self.count))
def move(self):
print("자동차({0} & {1})가 움직입니다.".format(self.size, self.count))
[8장: 145페이지]
In [18]:
car1 = Car2("big", 20)
car2 = Car2("small", 30)
자동차 객체의 수: Car2.count = 1
인스턴스 변수 초기화: self.count = 20
자동차 객체의 수: Car2.count = 2
인스턴스 변수 초기화: self.count = 30
클래스에서 사용하는 함수¶
인스턴스 메서드¶
[8장: 146 ~ 147페이지]
In [19]:
# Car 클래스 선언
class Car():
instance_count = 0 # 클래스 변수 생성 및 초기화
# 초기화 함수(인스턴스 메서드)
def __init__(self, size, color):
self.size = size # 인스턴스 변수 생성 및 초기화
self.color = color # 인스턴스 변수 생성 및 초기화
Car.instance_count = Car.instance_count + 1 # 클래스 변수 이용
print("자동차 객체의 수: {0}".format(Car.instance_count))
# 인스턴스 메서드
def move(self, speed):
self.speed = speed # 인스턴스 변수 생성
print("자동차({0} & {1})가 ".format(self.size, self.color), end='')
print("시속 {0}킬로미터로 전진".format(self.speed))
# 인스턴스 메서드
def auto_cruise(self):
print("자율 주행 모드")
self.move(self.speed) # move() 함수의 인자로 인스턴스 변수를 입력
[8장: 147페이지]
In [20]:
car1 = Car("small", "red") # 객체 생성 (car1)
car2 = Car("big", "green") # 객체 생성 (car2)
car1.move(80) #객체(car1)의 move() 메서드 호출
car2.move(100) #객체(car2)의 move() 메서드 호출
car1.auto_cruise() #객체(car1)의 auto_cruise() 메서드 호출
car2.auto_cruise() #객체(car2)의 auto_cruise() 메서드 호출
자동차 객체의 수: 1
자동차 객체의 수: 2
자동차(small & red)가 시속 80킬로미터로 전진
자동차(big & green)가 시속 100킬로미터로 전진
자율 주행 모드
자동차(small & red)가 시속 80킬로미터로 전진
자율 주행 모드
자동차(big & green)가 시속 100킬로미터로 전진
정적 메서드¶
[8장: 148 ~ 149페이지]
In [21]:
# Car 클래스 선언
class Car():
# def __init__(self, size, color): => 앞의 코드 활용
# def move(self, speed): => 앞의 코드 활용
# def auto_cruise(self): => 앞의 코드 활용
# 정적 메서드 @어노테이션
@staticmethod
def check_type(model_code):
if(model_code >= 20):
print("이 자동차는 전기차입니다.")
elif(10 <= model_code < 20):
print("이 자동차는 가솔린차입니다.")
else:
print("이 자동차는 디젤차입니다.")
[8장: 149페이지]
In [22]:
Car.check_type(25)
Car.check_type(2)
이 자동차는 전기차입니다.
이 자동차는 디젤차입니다.
클래스 메서드¶
[8장: 150페이지]
In [23]:
# Car 클래스 선언
class Car():
instance_count = 0 # 클래스 변수
# 초기화 함수(인스턴스 메서드)
def __init__(self, size, color):
self.size = size # 인스턴스 변수
self.color = color # 인스턴스 변수
Car.instance_count = Car.instance_count + 1
# def move(self, speed): => 앞의 코드 활용
# def auto_cruise(self): => 앞의 코드 활용
# @staticmethod
# def check_type(model_code): => 앞의 코드 활용
# 클래스 메서드
@classmethod
def count_instance(cls): #cls = 예외조항 -> 클래스로 호출해도 self처럼 적용
print("자동차 객체의 개수: {0}".format(cls.instance_count))
[8장: 150페이지]
In [24]:
Car.count_instance() # 객체 생성 전에 클래스 메서드 호출
car1 = Car("small", "red") # 첫 번째 객체 생성
Car.count_instance() # 클래스 메서드 호출
car2 = Car("big", "green") # 두 번째 객체 생성
Car.count_instance() # 클래스 메서드 호출
자동차 객체의 개수: 0
자동차 객체의 개수: 1
자동차 객체의 개수: 2
8.3 객체와 클래스를 사용하는 이유¶
[8장: 151페이지]
In [25]:
robot_name = 'R1' # 로봇 이름
robot_pos = 0 # 로봇의 초기 위치
def robot_move():
global robot_pos
robot_pos = robot_pos + 1
print("{0} position: {1}".format(robot_name, robot_pos))
[8장: 152페이지]
In [26]:
robot_move()
R1 position: 1
[8장: 152페이지]
In [27]:
robot1_name = 'R1' # 로봇 이름
robot1_pos = 0 # 로봇의 초기 위치
def robot1_move():
global robot1_pos
robot1_pos = robot1_pos + 1
print("{0} position: {1}".format(robot1_name, robot1_pos))
robot2_name = 'R2' # 로봇 이름
robot2_pos = 10 # 로봇의 초기 위치
def robot2_move():
global robot2_pos
robot2_pos = robot2_pos + 1
print("{0} position: {1}".format(robot2_name, robot2_pos))
[8장: 152페이지]
In [28]:
robot1_move()
robot2_move()
R1 position: 1
R2 position: 11
[8장: 153페이지]
In [29]:
class Robot():
def __init__(self, name, pos):
self.name = name # 로봇 객체의 이름
self.pos = pos # 로봇 객체의 위치
def move(self):
self.pos = self.pos + 1
print("{0} position: {1}".format(self.name, self.pos))
[8장: 153페이지]
In [30]:
robot1 = Robot('R1', 0)
robot2 = Robot('R2', 10)
[8장: 153페이지]
In [31]:
robot1.move()
robot2.move()
R1 position: 1
R2 position: 11
[8장: 153페이지]
In [32]:
myRobot3 = Robot('R3', 30)
myRobot4 = Robot('R4', 40)
myRobot3.move()
myRobot4.move()
R3 position: 31
R4 position: 41
8.4 클래스 상속¶
[8장: 155페이지]
In [33]:
class Bicycle():
def __init__(self, wheel_size, color):
self.wheel_size = wheel_size
self.color = color
def move(self, speed):
print("자전거: 시속 {0}킬로미터로 전진".format(speed))
def turn(self, direction):
print("자전거: {0}회전".format(direction))
def stop(self):
print("자전거({0}, {1}): 정지 ".format(self.wheel_size, self.color))
[8장: 156페이지]
In [34]:
class FoldingBicycle(Bicycle):
def __init__(self, wheel_size, color, state): # FoldingBicycle 초기화
Bicycle.__init__(self, wheel_size, color) # Bicycle의 초기화 재사용
#super().__init__(wheel_size, color) # super()도 사용 가능
self.state = state # 자식 클래스에서 새로 추가한 변수
def fold(self):
self.state = 'folding'
print("자전거: 접기, state = {0}".format(self.state))
def unfold(self):
self.state = 'unfolding'
print("자전거: 펴기, state = {0}".format(self.state))
[8장: 156페이지]
In [35]:
folding_bicycle = FoldingBicycle(27, 'white', 'unfolding') # 객체 생성
folding_bicycle.move(20) # 부모 클래스의 함수(메서드) 호출
folding_bicycle.fold() # 자식 클래스에서 정의한 함수 호출
folding_bicycle.unfold()
자전거: 시속 20킬로미터로 전진
자전거: 접기, state = folding
자전거: 펴기, state = unfolding
8.5 정리¶
'Python > 문법' 카테고리의 다른 글
파이썬 - 예외 처리 (0) | 2022.01.03 |
---|---|
파이썬 - 모듈 (0) | 2021.12.31 |
파이썬 - 클래스/모듈 (0) | 2021.12.30 |
파이썬 - 함수 (0) | 2021.12.30 |
파이썬 - 클래스 (0) | 2021.12.29 |
댓글