[Python] 16. 클래스와 객체의 본질
본 포스팅은 “윤성우의 열혈 파이썬 중급편” 책 내용을 기반으로 작성되었습니다. 잘못된 내용이 있을 경우 지적해 주시면 감사드리겠습니다.
16-1. 객체 안에 변수가 만들어지는 시점
- 클래스: 객체를 만들기 위한 일종의 설계도로써 클래스 내 들어갈 변수(데이터)와 메소드(기능)을 결정함
- 객체: 클래스를 기반으로 만들어진 실제 사물
class Simple:
# def __init__(self):
# self.i = 0
def seti(self, i):
self.i = i # 처음 이 문장 실행될 때 객체 내 변수 i가 만들어짐!
def geti(self): # 객체 내 변수 i가 생성 안됐는데 이 메소드가 호출되면 AttributeError 발생됨! 따라서 __init__로 객체 내 필요한 변수 초기화 필요!
return self.i
16-2. 객체에 변수와 메소드 붙였다 떼었다 해보기
class SoSimple:
def geti(self):
return self.i
ss = SoSimple()
ss.i = 27
ss.hello = lambda : print('Hello~')
ss.geti()
ss.hello()
del ss.i
del ss.hello
ss.geti()
ss.hello()
(결과) 27
Hello~
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in geti
AttributeError: 'SoSimple' object has no attribute 'i'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'SoSimple' object has no attribute 'hello'
16-3. 클래스에 변수 추가하기
class Simple:
def __init__(self, i):
self.i = i
def geti(self):
return self.i
Simple.n = 7 # 클래스에 속하는 변수 만듬
s1 = Simple(3)
s2 = Simple(5)
print(s1.n, s1.geti(), sep = ', ')
print(s2.n, s2.geti(), sep = ', ')
(결과) 7, 3
7, 5
이처럼 클래스에 속하는 변수를 만들 수 있으며, 객체에 찾는 변수가 없으면 해당 객체의 클래스로 찾아가서 해당 변수를 찾는다!
16-4. 파이썬에서는 클래스도 객체
지금까지 자료형을 확인하고자 할 때 마다 type 함수를 호출했다.
사실 type은 클래스의 이름이다.
type
(결과) <class 'type'>
만약 type이 함수였다면 <function type at ~> 으로 출력됐을 것이다.
아래 예제를 보자!
type([1, 2])
type(list)
class what:
pass
type(what)
(결과) <class 'list'>
<class 'type'>
<class 'type'>
이게 무엇을 의미할까?
<class 'list'>: 전달된 것이 list 클래스의 객체임
<class 'type'>: 전달된 것이 type 클래스의 객체임
정리하자면, 클래스도 객체이며, type이라는 클래스의 객체이다! 라고 할 수 있겠다.
이 사실을 안다면 아래 코드도 해석이 가능하다.
class what:
pass
what2 = what
w1 = what()
w2 = what2() # what은 객체이기 때문에 what2 라는 변수에 담아 객체를 생성할 수 있다!
Leave a comment