Python
Python 04 - OOP(Object oriented Programming) 객체 지향 프로그래밍
inderrom
2022. 12. 26. 16:59
자바를 우선 보자면 , extends로 상속 받는 게 가능하다.
<Animal.java>
package day03;
public class Animal {
int age = 1;
public void liveForAyear() {
age++;
}
}
<OopTest.java>
package day03;
public class OopTest {
public static void main(String[] args) {
Animal ani = new Animal();
System.out.println(ani.age);
ani.liveForAyear();
System.out.println(ani.age);
}
}
** 결과
<Human.java> - Animal을 상속받음
package day03;
public class Human extends Animal {
boolean flag_law = true;
public void makeWar() {
flag_law = false;
}
}
<OopTest.java>
package day03;
public class OopTest {
public static void main(String[] args) {
Human hum = new Human();
System.out.println(hum.age);
System.out.println(hum.flag_law);
hum.liveForAyear();
hum.makeWar();
System.out.println(hum.age);
System.out.println(hum.flag_law);
}
}
*
결과
Python
에서 자바와 똑같이 상속 받아보자!
<ooptest.py>
class Animal:
# 생성자 : __init__
def __init__(self):
self.age = 1
def liveForAyear(self):
# ++ 없으므로 += 해준다.
self.age+=1
# python은 생성할 때 new 생략 가능
ani = Animal()
print(ani.age)
ani.liveForAyear()
print(ani.age)
<ooptest02.py>
from day03.ooptest import Animal
ani = Animal()
print(ani.age)
ani.liveForAyear()
print(ani.age)
python에서 ooptest02를 실행시키는 경우
결과가 1,2,1,2, 두번씩 출력된다.
ooptest도 같이 출력되기 때문이다.
<ooptest.py>
class Animal:
def __init__(self):
self.age = 1
def liveForAyear(self):
# ++ 없으므로 += 해준다.
self.age+=1
def __del__(self):
print("소멸자")
if __name__ == '__main__':
ani = Animal()
print(ani.age)
ani.liveForAyear()
print(ani.age)
<ooptest.py>를 다시 고쳐서
__name__ == '__main__' : name이 main일 경우
출력이므로 이 조건을 주면 ooptest02에서 실행시켜도 두번 출력이 되지 않고
정상적으로 한 번 출력이 된다.
__del__ : 자바와 달리 소멸자가 존재한다. 메서드가 소멸될 때 실행된다.
class Human(Animal):
def __init__(self):
super().__init__()
self.flag_law = True
def makewar(self):
self.flag_law = False
if __name__ == '__main__':
hum = Human()
print(hum.flag_law)
print(hum.age)
hum.makewar()
hum.liveForAyear()
print(hum.flag_law)
print(hum.age)
python에서 상속을 받을 때에는 클래스명 옆에 () 안에 부모클래스명을 써준다.
자바와 다른 점을 상속 받을 때에는
super().__init__()을 써줘야한다. (생략하면 상속받아지지 않음)
다중상속
# 클래스 선언
class Biden:
def __init__(self):
self.idx_handsome = 10
def aging(self):
self.idx_handsome -= 1
class Bill:
def __init__(self):
self.money = 100
def breathe(self):
self.money += 1
class Oh:
def __init__(self):
self.idx_intellingence = 100
def chimae(self):
self.idx_intellingence -= 1
# 다중상속
class Sulah(Biden,Bill,Oh):
def __init__(self):
Biden().__init__()
Bill.__init__(self)
Oh.__init__(self)
# 상속받을 클래스의 생성자를 작성해준다.
if __name__ == '__main__' :
s = Sulah()
print(s.idx_handsome)
print(s.money)
print(s.idx_intellingence)
s.aging()
s.breathe()
s.chimae()
print(s.idx_handsome)
print(s.money)
print(s.idx_intellingence)