본문 바로가기
파이썬

파이썬 공부하기_클래스 (상속, 함수 오버라이딩, 연산자 + 오버라이딩)

by 혜룐 2015. 11. 10.
https://wikidocs.net/87
Person 이라는 부모클래스 /
Person
을 상속받은
Baby 클래스를 선언
class Baby(
Person
):
def eat(self):
return "bottle^^"
def play(self):
return "burning!"
부모클래스에
eat 이라는 함수를 오버라이딩
class Baby(
Person):
def eat(self):
return "bottle^^"
def play(self):
return "burning!"
Person 이라는 클래스를 선언하고, 
Baby 클래스는 Person을 상속받는다.
ptr 은 Person 인스턴스, zzazzan 은 Baby 인스턴스를. 그리고
eat이라는 메소드를 호출
해보자.
Baby 에 맞는 eat함수 결과가 나왔는지 확인하면 끝.
[a@tpl-master ~]$ cat Person.py 
#!/usr/bin/python
class Person:
eyes = 2
nose = 1
mouth = 1
ears = 2
def eat(self):
return "nam~ nam~ "
class Baby(Person):
def eat(self):
return "bottle^^"
def play(self):
return "burning!"
ptr = Person()
print ptr.eat()
zzazzan = Baby()
print zzazzan.eat()
,'\t', zzazzan.play()
[a@tpl-master ~]$ python Person.py 
Tae-Lyn( nam~ nam~ )
Zza-Zzan( bottle^^ ) burning!
[a@tpl-master ~]$ cat Person.py 
#!/usr/bin/python
class Person:
eyes = 2
nose = 1
mouth = 1
ears = 2
def __init__(self, name):
self.name = name
def eat(self):
return
self.name +
"( nam~ nam~ )"
class Baby(Person):
def eat(self):
return
self.name +
"( bottle^^ )"
def play(self):
return "burning!"
ptr =
Person('Tae-Lyn')
print ptr.eat()
zzazzan =
Baby('Zza-Zzan')
print zzazzan.eat() ,'\t', zzazzan.play()
연습. Kim씨네 부모클래스를
상속받은 Lee씨네 클래스
를 만들어 보기, 그리고
연산자 중 + 을 오버로딩
해보기
[root@tpl-master python]# cat inheritance.py 
#!/usr/bin/python
class HouseKim():
lastname="Kim"
def __init__(self, name):
self.fullname = self.lastname + name
def __add__(self, other):
return self.fullname+ " live in with " +other.fullname
def born(self, where):
return self.fullname+ " was born in " +where
aj = HouseKim('A-Jung')
print aj.born('Seoul')
class HouseLee(HouseKim):
lastname="Lee"
def liveIn(self, where):
return self.fullname+ " live in " +where
hr = HouseLee('H-Ryeon')
print hr.born('Seoul')
print hr.liveIn('Pusan')
print aj + hr
결과는..
[root@tpl-master python]# python inheritance.py 
KimA-Jung was born in Seoul
LeeH-Ryeon was born in Seoul
LeeH-Ryeon live in Pusan
KimA-Jung live in with LeeH-Ryeon