본문 바로가기
Language/Python

[Python] Object Oriented Programming

by 별토끼. 2019. 8. 14.
반응형

Object Oriented Programming

[중요 POINT] Object Oriented Programming, Class, Object(instance), Inheritance, Method Overriding, Operator Overloading ,Polymorphism

- object(객체) : 물체, 사물, 대상

- 객체지향 : 변수 + 함수

  • 객체를 생성해주는 Data Type - Class (user defined data type)
  • Method = 클래스 내 선언 함수

- C-struct

struct car{
	char color[10];
    int speed;
};
main(){
	struct car mycar1;
}
upSpeed(){}
downSpeed(){}

- Python - Class

class Car :
	color = ""
    speed = 0
    
    def upSpeed(self, value) :
    	self.speed += value
    
    def downSpeed(self, value) :
    	self.speed -= value

mycar1 = Car()
  • mycar1 = 객체
  • color, speed 에 대한 메모리가 생성된다.
  • self = 현재 나를 호출한 객체의 주소 (c++에서 this)
  • 위 예제에서는 mycar1의 주소가 self에 들어간다.

 

- instance 생성하기

myCar1 = Car()
myCar.color = "빨강"
myCar.speed = 0

myCar2 = Car()
myCar.color = "파랑"
myCar.speed = 0

myCar3 = Car()
myCar.color = "노랑"
myCar.speed = 0

myCar1.upSpeed(30)
myCar2.upSpeed(60)
myCar3.upSpeed(0)
print("자동자1의 색상은 %s, 현재 속도는 %d" %(myCar1.color, myCar1.speed))
  • 초기화는 어떻게 할까? 에 대한 궁금증이 생긴다.

 

- Constructor (생성자)

  • instance 생성 시 무조건 호출되는 메소드
  • 객체가 생성되면 시스템이 기본값을 설정하도록 하는 역할을 해준다.
class 클래스이름 :
	def __init__(self):
    	//이부분에 초기화할 코드 입력
  • 예시
class Car:
	color=""
    speed=0
    
    def __init__(self):
    	self.color="빨강"
        self.speed=0


myCar1 = Car() # 색상 빨강, speed 0
myCar2 = Car()

class Car:
	color=""
    speed=0
    
    def __init__(self, value1, value2):
    	self.color=value1
        self.speed=value2

#메인코드 부분
myCar1 = Car("빨강",30)
myCar1 = Car("파랑",60)

 

- Instance variable & Class variable

  • 인스턴스 변수 : 
  • Class변수 : Class안에 공간이 할당된 변수 (인스턴스간의 변수를 공유함)
class Car:
	color=""
    speed=0
    count = 0 
    
    def __init__(self):
    	self.color="빨강"
        self.speed=0
		Car.count+=1

myCar1 = Car()
myCar2 = Car()

#메인코드 부분
myCar1 = Car("빨강",30)
myCar2 = Car("파랑",60)
print("총 %d 대입니다"% myCar2.count)

 

- Inheritance

  • 기존 Class의 필드와 메소드를 그대로 물려받는 새로운 Class를 만드는 것.
  • 승용차에서는 좌석 수 알아보기 추가, 트럭에스는 적재량 알아보기 추가
  • --> 자동차 클래스를 상속받아 특정 메소드를 추가하면 효율적.
class Car:
    speed=0

	def upSpeed(self, value):
    	self.speed = self.speed+value

class Sedan(Car):
	seatNum = 0
    
    def getSeatNum(self):
    	return self.seatNum
        
class Sedan(Car):
	seatNum = 0
    
    def getCapacity(self):
    	return self.capacity

sedan1, truck1 = None, None

sedan1.upSpeed(100)
truck1.upSpeed(100)

 

반응형

'Language > Python' 카테고리의 다른 글

[Python] Method Overriding / Operator Overloading / Polymophism  (3) 2019.08.16
0710 Python 문법, 우분투 사용법  (0) 2019.07.10
[Python] Except / File  (0) 2017.08.17
[Python] Decorator  (0) 2017.08.16
[Python] Extends / super  (0) 2017.08.16

댓글