돈이 만드는 세상
#1-3 Python 초급 강의 - 클래스(class) 본문
클래스(class)
규약(class) & 객체, 인스턴스(object)
class
란 규약과 비슷하다고 소개합니다. 예를 들면, 집 설계도(class)가 존재하고 이를 통해 만들어 낸 집(객체)들인 것입니다. 파이썬에서 예시를 들면, list
들이 가지고 있는 값들은 서로 다르지만, list
가 가져야 할 특성(인덱스로 데이터 관리, 인덱싱 등)은 공통적으로 다 가지고 있습니다. 이 부분에서는 정의한 list가 객체(Object)
가 되는 것입니다.
구조
- 명사 : attribute, property, instance 변수
- 동사 : method
class 클래스이름:
- 명사(attribute)를 초기화 하는 공간
- 동사(behavior)를 정의하는 공간
클래스 정의/호출(=객체 만들기)
class SoccerPlayer:
def shoot(self):
print("슛을 날립니다.")
print("슈웃~")
def pass_the_ball(self):
print("패스를 합니다.")
player = SoccerPlayer()
player.shoot() # shoot() method 호출
player.pass_the_ball() # pass_the_ball() method 호출
player1 = SoccerPlayer()
player2 = SoccerPlayer()
player1.shoot()
player2.shoot()
class 내 method는 self
를 인자로 넣지 않으면 에러가 발생합니다.
attruibute 초기화(feat. 생성자)
class SoccerPlayer:
def __init__(self):
print("나 태어났어")
def shoot(self):
print("슛을 때립니다.")
player1 = SoccerPlayer() # __init__ 호출
class SoccerPlayer:
def __init__(self, height, weight):
print("나 태어났어")
self.wow_height = height
self.wow_weight = weight
def shoot(self):
self.wow_height = self.wow_height + 1
print("슛을 때립니다.")
player1 = SoccerPlayer(height = 180, weight = 50)
player2 = SoccerPlayer(160, 70)
player1.wow_height # 180 출력
player1.wow_weight # 50 출력
player2.wow_height # 160 출력
player2.wow_weight # 70 출력
player1.shoot() # => SoccerPlayer.shoot(player1)
player1.wow_height # 181 출력
__init__
은 객체를 생성할 때 무조건 호출되는 생성자라고 합니다.
상속(inheritence)
class Human: # class Human(object): object라는 것이 내부적으로 명시되어 있습니다. **init**을 정의하는 것도 object에 명시되어 있기 때문이라고 합니다.
def **init**(self, wow_weight, wow_height):
self.weight = wow_weight
self.height = wow_height
def walk(self):
print("걷습니다.")
h1 = Human(60, 170)
h1.walk() # 걷습니다. 출력
class Athlte(Human):
def __init__(self, wow_weight, wow_height, fat_rate):
super().__init__(wow_weight, wow_height)
self.fat_rate = fat_rate
def workout(self):
print("운동을 합니다.")
h2 = Athlte(50, 180, 11)
h2.walk() # 걷습니다. 출력
class SoccerPlayer(Athlete): # 부모에 대한 같은 함수에 대해 덮어씌우는 것을 override라고 합니다.
def workout(self):
print("축구를 한다.")
h3 = SoccerPlayer(50, 100, 12)
h3.walk() # 걷습니다. 출력
h3.workout() # 축구를 한다. 출력
상속을 하는 방법은 생성한 클래스명 옆에 상속을 받고 싶은 클래스의 이름을 기입하면 됩니다. 만일 클래스를 생성했을 때 부모의 생성자 외에 추가적인 attribute를 부여하고 싶다면 super()
라는 예약어를 사용하면 됩니다. super().__init__()
에 대한 호출은 필수는 아닙니다. 만약 부모의 생성자의 내용이 필요 없다면 super().__init__()
을 호출하지 않고, 일반 클래스에서 정의했던 것처럼 생성자를 정의하면 됩니다. 또한, super()
를 활용한 호출은 반드시 __init()__
메서드에만 적용되는 것이 아니라, 클래스 내에 정의 된 다른 메서드에도 그대로 정의할 수 있습니다.(e.g. super().METHOD())
파이썬 기본 자료형(클래스)별 api 살펴보기
- API(Application Programming Interface)
프로그래밍 언어, 라이브러리, 어플리케이션 등이 제공하는 기능들을 제어할 수 있게 만든 인터페이스. 파이썬에서 다루는 모든 자료형은 클래스의 객체라고 생각하면 된다고 합니다.
객체를 인스턴스(instance) 변수로 가지고 있기
class SoccerPlayer:
def __init__(self, weight):
self.weight = weight
def walk(self):
print("걷습니다")
a = SoccerPlayer(10)
a.weight # 10 출력
class SoccerCoach:
def __init__(self, num_career_year):
self.num_career_year = num_career_year
class Team:
def __init__(self, coach, player_list):
self.coach = coach
self.player_list = player_list
player1 = SoccerPlayer(70)
player2 = SoccerPlayer(50)
coach = SoccerCoach(10)
team = Team(
coach=coach,
player_list=[
player1,
player2,
]
)
#1
team.player_list[0].walk() # 걷습니다 출력
#2
player_list = team.player_list
player = player_list[0]
player.walk() # 걷습니다 출력
#3 안 좋은 코드의 예시
Team(
coach=coach,
player_list=[
SoccerPlayer(70),
SoccerPlayer(50),
]
).player_list[0].walk() # 걷습니다 출력
weight
이라는 매개변수에 int
, string
, list
등과 같이 어떤 데이터 타입이든지 전달할 수 있습니다. .
이 연속으로 표현되는 것을 (객체) method, functiond의 cascading
이라고 말합니다.
'프로그래밍 > Python' 카테고리의 다른 글
#3-1 파이썬 pandas 초급 강의(수정 필요) (0) | 2022.02.15 |
---|---|
#2 본격적인 파이썬 공부를 위한 계획표(2022/02/09) (0) | 2022.02.09 |
#1-4 파이썬 초급 강의 - 예외 처리(try/exception) (0) | 2022.02.07 |
#1-2 Python 초급강의 - 함수편 (0) | 2022.02.03 |
#1-1 Python 초급 강의 - 자료형 (0) | 2022.01.24 |