Python 클래스 :: 대화형 AI - mindscale
Skip to content

Python 클래스

x = 3

x의 자료형은 int이다. 자료형은 다른 말로 클래스(class)라고 한다.

type(x)
int

어떤 클래스의 값을 인스턴스라고 한다. 즉 x의 클래스는 int이면, xint의 인스턴스이다.

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('홍길동')

aspeak 메소드를 실행한다.

a.speak()
'My name is 홍길동.'

aage 속성을 확인한다.

a.age
0

add_age 메소드를 사용한다.

a.add_age(10)

다시 age 속성을 확인한다.

a.age
10

a의 자료형은 Person이다.

type(a)
__main__.Person

aPerson의 인스턴스인지 확인한다.

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('임꺽정')

bspeak 메소드를 사용한다.

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

bKorean의 인스턴스이다.

isinstance(b, Korean)
True

KoreanPerson의 서브클래스이므로 bPerson의 인스턴스이기도 하다.

isinstance(b, Person)
True