01. Class 만들기
- class는 객체를 만들기 위한 청사진이다.
- class를 파이썬에서는 다음과 같이 만들 수 있다.
- PascalCase : 모든 단어, 이름, 성 앞 글자를 대문자로 한다.
- camelCase : 두 번째 단어의 첫 시작을 대문자로 한다.
- snakecase : 모든 글자가 소문자이고, 각 글자들 사이는 로 이어져있다.
- 파이썬에서는 class의 이름에는 PascalCase가 쓰이고, 나머지는 모두 snake_case로 이뤄진다.
02. 속성, 클래스 생성자, init() 함수 활용하기
- 클래스의 모든 객체들에게 속성을 부여하려면 코드상의 오류를 발생시킬 수 있음.
- 이럴 때 생성자를 만들어야 함. 생성자는 청사진의 일부로, 객체가 생성될 때 어떤 일이 일어나야 하는지 명시하는 것임.
- initialize : to set (variables, counters, switches, etc.) to their starting values at the beginning of a program or subprogram. / to clear of previous data in preparation for use.
- 객체가 초기화 될 때 변수나 카운터를 지정할 수 있음.
- 파이썬에서는 생성자를 만들려면 init 함수라는 특별한 함수를 사용해야 함.
class User:
def __init__(self):
self.name = "yoon"
user_1 = User()
print(user_1.name)
class User:
def __init__(self,seats):
self.seats = seats
my_car = User(5)
print(my_car.seats)
class User:
def __init__(self,user_id, username):
self.id = user_id
self.username = username
self.followers = 0
user_1 = User("001","angela")
user_2 = User("002","jack")
print(user_1.followers)
03. 클래스에 메소드 추가하기
class User:
def __init__(self,user_id, username):
self.id = user_id
self.username = username
self.followers = 0
self.following = 0
def follow(self,user):
user.followers +=1
self.following +=1
user_1 = User("001","angela")
user_2 = User("002","jack")
user_1.follow(user_2)
print(user_1.followers)
print(user_1.following)
print(user_2.followers)
print(user_2.following)
04. quiz
from question_model_day_17 import Question
from data_day_17 import question_data
question_bank = []
for question in question_data:
question_text = question["text"]
question_answer = question["answer"]
new_question = Question(question_text, question_answer)
question_bank.append(new_question)
print(question_bank[0])