티스토리 뷰

개와 고양이를 추상화 해보자


그리고 다음과 같이 정의했다.


class Cat:
def __init__(self, name, weight=1):
self.name = name
self.weight = weight

def sleep(self):
print("{} sleep...".format(self.name))

def feed(self, food):
self.weight += food

def __str__(self):
return "name={} weight={}".format(self.name, self.weight)

def grooming(self):
print("{} grooming!".format(self.name))


class Dog:
def __init__(self, name, weight=1):
self.name = name
self.weight = weight

def sleep(self):
print("{} sleep...".format(self.name))

def feed(self, food):
self.weight += food

def __str__(self):
return "name={} weight={}".format(self.name, self.weight)

def howl(self):
print("{} howl!".format(self.name))

고양이와 개의 공통의 특징(attribute) 들이 보인다.


이것을 굳이 개와 고양이에 중복되어 정의할 필요가 없다.


또한 개념적으로 이것들은 개의 특징도 고양이의 특징도 아닌


동물의 특징으로 봐야 한다.


동물 클래스를 만들고 이것을 상속하여 보자.


Animal 이란 클래스를 만들고 개와 고양이가 각각 상속하였다.


class Animal:
def __init__(self, age=1, weight=1):
self.age = age
self.weight = weight

def sleep(self):
print("sleep...")

def feed(self, food):
self.weight += food

def __str__(self):
return "age={} weight={}".format(self.age, self.weight)


class Cat(Animal):
def grooming(self):
print("grooming!")


class Dog(Animal):
def howl(self):
print("howl!")


상속한 클래스에서는 부모클래스의 특징을 자식 클래스에서 새로 정의 하지 않는 이상 그래도 사용가능하다.


개와 고양이에서는 동물의 특징을 제외한 개의 특징 고양이의 특징만 정의 하였다.


코드가 한결 나아 젔다.


[overriding: 오버라이딩]


부모클래스에서 정의한 함수를 새로 정의해야 할때가 있다.


class Animal:
def __init__(self, age=1, weight=1):
self.age = age
self.weight = weight

def sleep(self):
print("sleep...")

def feed(self, food):
self.weight += food

def __str__(self):
return "age={} weight={}".format(self.age, self.weight)


class Cat(Animal):
def sleep(self):
print("cat sleep...")

def grooming(self):
print("grooming!")


sleep 이란 함수를 자식 클래스에서 새로 정의하면


부모클래스의 정의는 무시되고 자식클래스의 정의가 우선시 된다.

댓글