Python

[Python] 클래스

아잠만_ 2024. 6. 26. 12:32

클래스 예시

java

package day04;

public class Animal {
	int cnt_leg = 4;
	
	void shottedLeg(int shot) {
		cnt_leg -= shot;
	}
}
package day04;

public class OopTest01 {
	public static void main(String[] args) {
		Animal ani = new Animal();
		
		System.out.println(ani.cnt_leg);
		ani.shottedLeg(1);
		System.out.println(ani.cnt_leg);
	}
}

python

class animal :
    def __init__(self): # 생성자
        self.cnt_leg = 4 # self 지역변수
        
    def shottedLeg(self, shot):
        self.cnt_leg -= shot
        
ani = animal() #변수와 new 생략
print(ani.cnt_leg)
ani.shottedLeg(1)
print(ani.cnt_leg)

클래스 생성

class 클래스명 :
	def __init__(self) : # 생성자 역할, self는 java와 this와 유사
    	self.기본변수 = 값 #해당 클래스의 기본 변수
    
    def 메서드(self, 매개변수)
    	self.변수 = 변동값

다른 곳에서 animal클래스 불러오기

1. 직접 해당 py를 불러왔을 경우

from day04.animal import animal

ani = animal() #변수와 new 생략
print(ani.cnt_leg)
ani.shottedLeg(2)
print(ani.cnt_leg)

2. 해당 패키지만 불러오는 경우

from day04 import animal

ani = animal.animal() #변수와 new 생략
print(ani.cnt_leg)
ani.shottedLeg(2)
print(ani.cnt_leg)

이 때 실행하는 경우에 2개의 출력이 아니라 4개의 출력이 생기는데

이것은 animal.py에 있는 출력 문장 때문이다

python이 스크립트 언어이기 때문에 순차적으로 출력하기 때문에 발생하는 문제이며

해당 하는 것을 실행하지 않기 위해서 main 함수 안에 넣어야한다

if __name__ == '__main__':
class animal :
    def __init__(self): # 생성자
        self.cnt_leg = 4 # self 지역변수
        
    def shottedLeg(self, shot):
        self.cnt_leg -= shot

if __name__ == '__main__':           
    ani = animal() #변수와 new 생략
    print(ani.cnt_leg)
    ani.shottedLeg(2)
    print(ani.cnt_leg)

클래스 예시 2 - 소멸자 등

class Car:
    def __init__(self): # 생성자
        self.cnt_wheel = 4
        print("생성자")
        
    def platTire(self,cnt):
        self.cnt_wheel -= cnt
    
    def __del__(self): # 소멸자
        print("소멸자")
        
    def __str__(self): # toString
        return "휠수량 : "+str(self.cnt_wheel)

if __name__ == '__main__':
    c = Car() # 생성자
    print(c) # 휠수량 : 4
    print(c.cnt_wheel) # 4
    c.platTire(1)
    print(c.cnt_wheel) # 3
    # 소멸자

상속 예시

java

package day04;

public class Human extends Animal{
	int skill_lang = 0;
	
	void momstouch(int stroke) {
		skill_lang += stroke;
	}
}
package day04;

public class OopTest02 {
	public static void main(String[] args) {
		Human hum = new Human();
		System.out.println("leg : "+hum.cnt_leg);
		System.out.println("lang : "+hum.skill_lang);
		
		hum.shottedLeg(2);
		hum.momstouch(5);
		
		System.out.println("leg : "+hum.cnt_leg);
		System.out.println("lang : "+hum.skill_lang);
	}
}

python

from day04.animal import animal
class Human(animal):
    def __init__(self):
        super().__init__() # 상속
        self.skill_lang = 0
    
    def momstouch(self, stroke):
        self.skill_lang += stroke
        

if __name__ == '__main__':
    h = Human()
    print("leg", h.cnt_leg)
    print("lang", h.skill_lang)
    
    h.shottedLeg(2)
    h.momstouch(5)
    
    print("leg", h.cnt_leg)
    print("lang", h.skill_lang)
from day04.human import Human

h = Human()
print("leg", h.cnt_leg)
print("lang", h.skill_lang)
    
h.shottedLeg(2)
h.momstouch(5)
    
print("leg", h.cnt_leg)
print("lang", h.skill_lang)

상속

class Child(Parent) :
	def __init__(self):
    	super().__init__()
        self.자식변수 = 값
        
	def 자식함수(self, 매개변수) :
		self.자식변수 += 변동값

다중상속 예제

java

package day04;

public class Duck {
	int feather = 100000;
	
	void molting(int feather) {
		this.feather -= feather; 
	}
}
package day04;

public class Bird {
	int flying = 5;
	
	void practiceFlying(int flying) {
		this.flying += flying;
	}
}

자바는 다중 상속이 안되기 때문에 부모 클래스만 생성 후 python으로 변환 예제

python

class Bird :
    def __init__(self):
        self.flying = 5
    def practiceFlying(self, flying):    
        self.flying += flying
        
class Duck:
    def __init__(self):
        self.feather = 100000
        
    def molting(self, feather):
        self.feather -= feather
from day04.bird import Bird, Duck
class Azamman(Bird, Duck):
    def __init__(self):
        Bird.__init__(self)
        Duck.__init__(self)
        # 다중상속을 받은 클래스에서 super()를 통해 접근한다면
        # 순서상 맨 앞 클래스로 접근하기 때문에 모든 부모클래스의 생성자를 호출하기 위해서
        # 명시적으로 각 부모클래스의 이름을 통해 접근
        self.age = 5
    def growOld(self):
        self.age +=1
        
if __name__ == '__main__':
    a = Azamman()
    print("나이", a.age)
    print("깃털수", a.feather)
    print("비행실력", a.flying)
    
    a.growOld()
    a.molting(100)
    a.practiceFlying(10)
    
    print("나이", a.age)
    print("깃털수", a.feather)
    print("비행실력", a.flying)

다중상속

class Child(Parent1, Parent2) :
	def __init__(self):
    	Parent1.__init__()
    	Parent2.__init__()
    	self.자식변수 = 값
        
	def 자식함수(self, 매개변수) :
    	self.자식변수 += 변동값