comedian이 class
comedian의 실체(instance)는 이영자,송영이,양세형,유병재이다.
이 instance들을 object(객체)라고 한다.
-class 키워드 사용
class ClassName:
..class 내용 코드
class이름은 각 단어의 앞글자를 대문자로 사용한다.
한단어 이상으로 이루어져있다면 밑줄없이 단어를 붙이되 각 단어의 앞글자는 대문자로해서 단어를 구분한다.
ex)ScotchWishkey
클래스가 정의되면, 클래스로부터 실체화(instantiate) 할 수 있다.
hyundai = Car()
bmw = Car()
hyundai 와 bmw는 객체(object)이다. 아직 Car class는 비어있는 상태이다.
부류의 공통점을 찾자! 자동차라면 브랜드,엔진의 마력, 연비 등
class에 정의되는 공통 요소들을 전문어로 class의 attribute(성질 혹은 속성) 이라고 한다.
속성들을 class에서 정의하기 위해서는 __init__
함수를 통해서 정의 하면 된다.
class 안에서 정의해주는 함수(function)는 function이라고 하지 않고 method 라고 한다
class Car:
def __init__(self,maker,model,horse_power):
self.maker =maker
self.model =model
self.horse_power = horse_power
__init__
메소드__init__
처럼 앞뒤로 밑줄 2개가 있는 메소드들을 special method라고 한다.
class가 실체화 될때 사용되는 함수이다.
hyundai = Car("현대","제네시스",500)
__init__
메소드를 부르지않았지만 클래스가 실체화될때 자동으로 __init__
메소드가 호출된다.
위에서 __init__
의 인자는 4개였는데 왜 3개만 넘겨주었는가?
self인자를 빼먹었는데 ... 이것은 굉장히 어렵다..
self는 실체를 가르키는 단어이다. 고로 class의 실체인 객체를 가르킨다.
여기서 hyundai 나 bmw를 가르킨다.
그리고 클래스를 실체화할 때 파이썬이 해당 객체 (self)를 __init__
함수에 넘겨준다 .
Method와 attribute(속성)의 차이는 명사와 동사의 차이
속성은 해당 객체의 이름 등의 정해진 성질인 반면에 메소드는 move, eat 등 객체가 행할 수 있는 어떠한 action같은 느낌!
경적울리기 메소드를 추가한다면
class Car:
def __init__(self, maker, model, horse_power):
self.maker = maker
self.model = model
self.horse_power = horse_power
def honk(self):
return "빠라바라빠라밤"
모든 메소드에는 self인자가 첫번째 인자로 들어가야한다.
hyundai = Car("현대", "제네시스", 500)
hyundai.honk()
> "빠라바라빠라밤"
처음 내가 쓴 답.. 진짜 못하네 ^^
class Database:
def __init__(self,name,size):
self.name = name
self.size = size
def insert(self,field,value):
self.field = field
self.value = value
if len(self.name) > size:
pass
def select(self,field):
if len(self.name) == 0:
return None
else:
return self.name
def update(self,field,value):
if len(field) == 0:
pass
def delete(self,field):
if len(field) == 0:
pass
2시간동안 푼 정답:
class Database:
def __init__(self,name,size):
self.name = name
self.size = size
self.data = {}
def insert(self,field,value):
if len(self.data) < self.size:
self.data[field] = value
def select(self,field):
if field in self.data:
return self.data[field]
else:
return None
def update(self,field,value):
if field in self.data:
self.data[field] = value
def delete(self,field):
if field in self.data:
del self.data[field]