Python 클래스
x = 3
x의 자료형은 int
이다. 자료형은 다른 말로 클래스(class)라고 한다.
type(x)
int
어떤 클래스의 값을 인스턴스라고 한다. 즉 x
의 클래스는 int
이면, x
는 int
의 인스턴스이다.
isinstance(x, int)
True
1, 2, 3, 4, .. 등등이 모두 int
의 인스턴스다.
isinstance(2, int)
True
클래스 만들기
새로운 클래스를 정의한다.
class Person:
def __init__(self, name):
self.name = name
self.age = 0
def speak(self):
return f'My name is {self.name}.'
def add_age(self, year):
self.age += year
Person
클래스의 인스턴스 a
를 만든다.
a = Person('홍길동')
a
의 speak
메소드를 실행한다.
a.speak()
'My name is 홍길동.'
a
의 age
속성을 확인한다.
a.age
0
add_age
메소드를 사용한다.
a.add_age(10)
다시 age
속성을 확인한다.
a.age
10
a
의 자료형은 Person
이다.
type(a)
__main__.Person
a
가 Person
의 인스턴스인지 확인한다.
isinstance(a, Person)
True
서브클래스
Person
의 서브클래스인 Korean
을 정의한다.
class Korean(Person):
def __init__(self, name):
super().__init__(name)
self.age = 1
def speak(self):
return f"My name is {self.name}. Do you know Yuna Kim?"
Korean
의 인스턴스 b
를 만든다.
b = Korean('임꺽정')
b
의 speak
메소드를 사용한다.
b.speak()
'My name is 임꺽정. Do you know Yuna Kim?'
age
속성을 확인한다.
b.age
1
add_age
메소드를 사용한다. Korean
클래스에는 add_age
메소드가 별도로 정의되어 있지 않으므로 상위 클래스인 Person
의 메소드가 실행된다.
b.add_age(10)
age
속성을 다시 확인한다.
b.age
11
b
의 자료형은 Korean
이다.
type(b)
__main__.Korean
b
는 Korean
의 인스턴스이다.
isinstance(b, Korean)
True
Korean
이 Person
의 서브클래스이므로 b
는 Person
의 인스턴스이기도 하다.
isinstance(b, Person)
True