반응형
oop : object oriented program : 객체 지향(상속) 프로그램
object를 상속받아서 시작되는 프로그램
자바는 1파일 1클래스인데 다른 언어는 아니다. 여러 클래스 가능!
python에서의 클래스를 만들어보자!
class Vehicle:
def __init__(self):
print("부모생성자")
self.cnt_wheel = 2
def addWheel(self):
self.cnt_wheel += 2
def __del__(self):
print("부모소멸자")
v = Vehicle()
print(v.cnt_wheel)
v.addWheel()
print(v.cnt_wheel)
기본 생성자를 __init__으로 만든다.
기본 생성자에 전역변수를 선언한다.
괄호안에 self를 넣는다.
del로 소멸시킨다.
상속받는 클래스도 해보자.
class Car(Vehicle) :
def __init__(self, ):
self.amount_fuel = 0
super().__init__()
def mantangk(self):
self.amount_fuel = 100
def onedollor(self):
if self.amount_fuel >= 100 :
print("만땅이유")
return;
self.amount_fuel += 1
def __del__(self):
print("자식소멸자")
c = Car()
print(c.cnt_wheel)
print(c.amount_fuel)
c.addWheel()
c.mantangk()
c.onedollor()
print(c.amount_fuel)
print(c.cnt_wheel)
1. extend쓰는 것이 아니라 괄호 안에 부모 클래스를 넣어준다.
2. 생성자에 super()의 생성자를 부른다.
< Python의 main >
1.
class Trump:
def __init__(self):
self.cnt_building = 50
def maemae(self,cnt):
self.cnt_building+=cnt
if __name__ == '__main__':
t = Trump()
print(t.cnt_building)
t.maemae(7)
print(t.cnt_building)
from day03.ooptest02 import Trump
if __name__ == '__main__':
t = Trump()
print(t.cnt_building)
t.maemae(10)
print(t.cnt_building)
2.
package day03;
public class Trump {
int cnt_building = 50;
public void maemae(int cnt) {
cnt_building += cnt;
}
public static void main(String[] args) {
Trump t = new Trump();
System.out.println(t.cnt_building);
t.maemae(7);
System.out.println(t.cnt_building);
}
}
package day03;
public class TrumpTest {
public static void main(String[] args) {
Trump t = new Trump();
System.out.println(t.cnt_building);
t.maemae(10);
System.out.println(t.cnt_building);
}
}
1번과 2번은 같은 내용을 파이썬과 자바로 작성한 것이다.
파이썬에서 main 메서드를 쓰지 않으면 객체를 생성했을 때 검증하기 위해 실행해보았던 내용까지도 불러와졌다.
파이썬에서의 main 메서드를 사용하는 용도를 배울 수 있다.
다중상속
class LeeJY:
def __init__(self):
self.pocket = ["삼성전자"]
def insu(self,company_name):
self.pocket.append(company_name)
class Trump:
def __init__(self):
self.cnt_building = 50
def maemae(self,cnt):
self.cnt_building+=cnt
if __name__ == '__main__':
t = Trump()
print(t.cnt_building)
t.maemae(7)
print(t.cnt_building)
이 두 클래스를 상속받아 보자!
from day03.ooptest02 import Trump
from day03.ooptest04 import LeeJY
class KimJH(LeeJY, Trump):
def __init__(self):
LeeJY.__init__(self)
Trump.__init__(self)
if __name__ == '__main__':
K = KimJH()
print(K.cnt_building)
print(K.pocket)
K.maemae(10)
K.insu("애플")
print(K.cnt_building)
print(K.pocket)
엄청난 부자 만들기 성공--!
JFrame
wys i wyg : 갖다쓰면 내꺼!
반응형
'내가 보려고 정리하는 > Python' 카테고리의 다른 글
JFrame swing 베이스볼게임/ python ui 전화기 만들기 - 230224 (0) | 2023.02.24 |
---|---|
JFrame - 230222 (0) | 2023.02.22 |
Python의 메서드(1) - 230220(2) (0) | 2023.02.20 |
Python의 반복문 - 230220 (0) | 2023.02.20 |
Python의 변수, if - 230217 (0) | 2023.02.18 |