Bootcamp/Pandas & python
[Python] 클래스 (python)
K_Hyul
2023. 10. 5. 09:13
728x90
클래스는 객체를 만들기 위한 설계도라 생각하면 편하다.
class GrandMother : # 클래스 : 설계도
family = "grandparents" # 속성 : 클래스 내부 변수
def print_self(self): # 안에 함수
print(self.family)
Lee = GrandMother()
Lee.print_self()
__init__ 함수를 써야 하는 이유는 원하는 생성자를 형성하기 때문이다. (안할 시 자동으로 생성)
객체를 만들 때 필요한 작업이 있으면 생성자를 작성해서 실행 시킬 수 있다.
def __init__(self, name, age):
self.name = name # 선언시 name, age를 받아야함 아니면 오류 default값을
self.age = age # 입력 받은 값
self.home = "Seoul" # default 값
상속은
클래스에서 public 인 경우 그냥 self.name 이렇게 선언하고
private 인 경우 self.__age 이렇게 선언한다.
private 로 선언하면 외부에서 접근이 불가능해서
위 Lee.__age 이렇게 하는 순간 에러가 뜬다.
class Vehicle: # 탈것을 예시로 했을 때
def __init__(self, wheel_cnt = 0, rider_num = 0): # default 값을 0으로 처리
self.wheel_cnt = wheel_cnt
self.rider_num = rider_num
def backward(self):
print("뒤로 이동")
def forward(self):
print("앞으로 이동")
class Moto(Vehicle):
def __init__(self):
super().__init__(wheel_cnt=2, rider_num = 1)
def jump(self):
print("점프 한다")
def backward(self): # 부모와 이름이 같은 함수로 차이점 호출시 이거만 나옴을 볼 수 있다.
print("앞바퀴를 들고 후진")
class Boat(Vehicle):
def __init__(self, div : bool = False):
super().__init__(rider_num = 4)
self.div = div
def forward(self): # 부모와 이름이 같은 함수로 호출시 부모 함수가 아닌 이게 나온다.
print("항해 한다")
def diving(self):
if (self.div):
print("잠수 한다")
else:
print("잠수 불가")
vehicle = Vehicle()
vehicle.backward()
moto = Moto()
moto.backward()
print(moto.rider_num)
boat = Boat(True) # 잠수가 된다로 True를 넣음
print(boat.rider_num)
boat.diving()
super에서 default 값을 수정하는게 가능한 것을 볼 수 있다.
즉 부모와 다른 default는 super().__init__()에서 변경하는게 옳다 본다.
728x90