>>> type(3)
<class 'int'>
>>> type(3.1)
<class 'float'>
>>> type('3')
<class 'str'>
>>> type([])
<class 'list'>
>>> type(())
<class 'tuple'>
>>> def foo():
pass
>>> type(foo)
<class 'function'>
클래스 정의 및 인스턴스 생성
>>> class BusinessCard:
pass
>>> card1 = BusinessCard()
>>> card1
<__main__.BusinessCard object at 0x03DC9E90>
>>> type(card1)
<class '__main__.BusinessCard'>
# 메모리 주소 0x03DC9E90에 BusinessCard클래스의 인스턴스가 생성되었고 이를 card1변수가 바인딩함.
클래스에 메서드 추가
>>> class BusinessCard:
def set_into(self, name, email, addr):
# 인스턴스변수(self.xxx)에 인자 바인딩
self.name = name
self.email = email
self.addr = addr
>>> member1 = BusinessCard()
>>> member1.set_into("Yuna Kim", "yunakim@naver.com", "Seoul")
# 인스턴스 변수 호출
>>> member1.name
'Yuna Kim'
>>> member1.email
'yunakim@naver.com'
>>> member1.addr
'Seoul'
>>> class BusinessCard:
def set_into(self, name, email, addr):
self.name = name
self.email = email
self.addr = addr
def print_info(self):
print("-------------------------")
print("Name: ", self.name)
print("E-mail: ", self.email)
print("Address: ", self.addr)
print("-------------------------")
>>> member2 = BusinessCard()
>>> member2.print_info()
# 인스턴스 변수에 바인딩 되어있지 않을때 print_info()함수 사용시 에러
-------------------------
Traceback (most recent call last):
File "<pyshell#67>", line 1, in <module>
member2.print_info()
File "<pyshell#65>", line 8, in print_info
print("Name: ", self.name)
AttributeError: 'BusinessCard' object has no attribute 'name'
>>> member2.set_into("yooil", "yooil405@naver.com", "Seoul")
# 메서드는 뒤에 () 붙여줘야 함. 아닐경우 인스턴스 주소 알려줌.
>>> member2.print_info
<bound method BusinessCard.print_info of <__main__.BusinessCard object at 0x03E53D90>>
>>> member2.print_info()
-------------------------
Name: yooil
E-mail: yooil405@naver.com
Address: Seoul
-------------------------