클래스의 6가지 필수 요소
멤버변수의 속성: 파이썬에서는 private public이 존재
private: 멤버접근연산자를 통해 멤버변수나 메소드에 직접 접근이 불가능. 언더바 2개를 붙여서 만든다.
class Point2D:
def __init__(self, x, y):
# 멤버변수의 속성: 파이썬에서는 private public이 존재
# private: 멤버접근연산자를 통해 멤버변수나 메소드에 직접 접근이 불가능. __(언더바) 2개를 붙여서 만든다.
self.__x = x
self.__y = y
# get 메소드
def get_coord(self):
return (self.__x, self.__y)
def get_x(self):
return self.__x
def get_y(self):
return self.__y
# setter 메소드: 멤버변수를 변경하고 싶을 때 사용
def set_coord(self, x, y):
self.__x = x
self.__y = y
point = Point2D(1,1)
#print(point.__x)
point.__x = 3
print(point.get_x())
print(point.get_xy())
print("변경 후")
point.set_coord(2, 2)
print(point.get_x())
print(point.get_xy())
동일한 기능을 또 구현할 필요 없기 때문에 클래스의 상속을 활용한다.
상속을 받기 위해서는 괄호를 사용해서 부모 클래스의 이름을 적어줘야한다.
부모 클래스와 자식 클래스로 구분
자식 클래스는 부모클래스의 private 멤버변수에 접근하지 못하기 때문에 getter를 사용해야한다.
메소드 오버라이딩: 부모클래스의 메소드를 자식클래스에서 재 정의
super()
: 부모클래스 호출
# 상속을 받기 위해서는 괄호를 사용해서 부모 클래스의 이름을 적어줘야한다.
# Point3D 클래스를 Point2D의 자식 클래스라고 한다.
class Point3D(Point2D):
def __init__(self, x, y, z):
#super() 부모클래스 호출
super.__init__(x, y)
# 자식클래스는 왜 get_x()를 썼을까? 자식클래스는 부모클래스의 private 멤버변수에 접근하지 못한다!
# 따라서 getter를 써야한다.
self.__x = super().get_x()
self.__y = super().get_y()
self.__z = z
# 메소드 오버라이딩: 부모클래스의 메소드를 자식클래스에서 재 정의
def get_coord(self):
return(self.__x, self.__y. self.__z)
def self_coord(self, x, y, z)
self.__x = x
self.__y = y
self.__z = z
def get_z(self):
return self.__z
point2 = Point3D(1, 1, 1)
print(point2.get_x())
print(point2.get_z())