오늘은 파이썬의 클래스, muteable 자료형과 immutable 자료형에 대해 공부해 보았다.
먼저 class에 대해 알아보면
클래스를 선언하는것은 과자 틀을 만드는 것이고, 선언된 과자틀(class)로 과자(instance)를 만든다고 생각하면 됩니다. 선언 후 바로 사용되는 함수와 다르게 클래스는 인스턴스를 생성하여 사용하게 됩니다. class 내부에 선언되는 메소드는 기본적으로 self라는 인자를 가지고 있습니다. self는 클래스 내에서 전역 변수와 같이 사용됩니다. # 용어 정리 - 인스턴스(instance) : class를 사용해 생성된 객체 - 메소드(method) : 메소드란 클래스 내에 선언된 함수이며, 클래스 함수라고도 한다. - self : 메소드를 선언할 때에는 항상 첫번째 인자로 self를 넣어줘야 한다.
class CookieFrame(): # CookieFrame이라는 이름의 class 선언
def set_cookie_name(self, name):
self.name = name
cookie1 = CookieFrame()
cookie2 = CookieFrame()
cookie1.set_cookie_name("cookie1") # 메소드의 첫 번째 인자 self는 무시된다.
cookie2.set_cookie_name("cookie2")
print(cookie1.name) # cookie1
print(cookie2.name) # cookie2
## class의 기본 구조
이정도 된다.
일단 클래스를 사용해 사용자들의 프로필을 관리하고 찾아볼 수 있는 코드를 짜보았다.
from pprint import pprint
class Profile:
def __init__(self):
self.profile = {
"name": "-",
"gender": "-",
"birthday": "-",
"age": "-",
"phone": "-",
"email": "-",
}
def set_profile(self, profile):
self.profile = profile
def get_profile(self):
return self.profile
def get_name(self):
return self.profile.get('name')
def get_gender(self):
return self.profile.get('gender')
def get_birthday(self):
return self.profile.get('birthday')
def get_age(self):
return self.profile.get('age')
def get_phone(self):
return self.profile.get('phone')
def get_email(self):
return self.profile.get('email')
profile = Profile()
profile.set_profile({
"name": "lee",
"gender": "man",
"birthday": "01/01",
"age": 32,
"phone": "01012341234",
"email": "python@sparta.com",
})
information = input("궁금하신 정보를 입력하세요. (ex): 이름, 성별, 생일, 나이, 핸드폰번호, 이메일) ※전체를 보시려면 전체 를 입력해주세요 : ")
if information == "이름":
print(profile.get_name()) # 이름 출력
elif information == "성별":
print(profile.get_gender()) # 성별 출력
elif information == "생일":
print(profile.get_birthday()) # 생일 출력
elif information == "나이":
print(profile.get_age()) # 나이 출력
elif information == "핸드폰번호":
print(profile.get_phone()) # 핸드폰번호 출력
elif information == "이메일":
print(profile.email()) # 이메일 출력
elif information == "전체":
pprint(profile.get_profile())
else:
print("잘못 입력하셨습니다.")
'TTL > 1주차 ~ 4주차 TIL (8.29 ~ 9.23)' 카테고리의 다른 글
2022-09-15 TIL (0) | 2022.09.16 |
---|---|
2022-09-14 TIL (0) | 2022.09.15 |
2022-09-08 TIL (0) | 2022.09.12 |
2022-09-07 TIL (1) | 2022.09.07 |
2022-09-06 TIL (0) | 2022.09.06 |