Class and Instance, Construct, Destructor
Language/Python

Class and Instance, Construct, Destructor

뉴비뉴 2020. 6. 2.

시작하기전에

어떠한 설계도(Class)를 바탕으로 여러 집(Instance)들을 만들어내는 것은 instantiation 한다고 한다.

 

 

Class

클래스는 함수와 변수로 이루어져 있습니다.

 

class MyHome:
     colorRoof = 'red'
     stateDoor = 'closed'
     def paintRoof(self, color):
         self.colorRoof = color
     def openDoor(self):
         self.stateDoor = 'open'
     def closeDoor(self):
         self.stateDoor = 'close'
     def printStatus(self):
         print("Roof color is", self.colorRoof, ", and door is", self.stateDoor)
         
homeAtSeoul = MyHome()  # 생성자를 call하는 함수 콜 return 값은 함수를 통해서 만들어진 하나의 인스턴스가 리턴됩니다.
homeAtPaju = MyHome()

if homeAtSeoul is homeAtPaju: # 를 수행한다면 False가 출력됩니다.
# 하나의 클래스로 만들어졌지만 인스턴스의 주소는 각자 다르기 때문입니다.

인스턴스의 레퍼런스는 다르다.

homeAtSeoul.openDoor()  # homeAtSeoul 인스턴스 속에 있는 함수를 호출한다.
homeAtPaju.paintRoof('blue')  # 위와 동일

Important Methods in Class (Constructor, Destructor)

Constructor

클래스 안에는 변수와 함수가 존재합니다.

Called when instaniated 인스턴스가 만들어질 때 호출되는

하나의 인스턴스를 만드는 시점 때 Contstructor가 호출 됩니다.

Constructor 안에 self는 리턴되는 것이 self가 된다.

def __init__(self, . . .)  # Constructor

 

Destructor

많이 사용되지는 않지만 유용하게 사용할 수 있습니다.

아래 예시를 보면 del homeAtSeoul로 인스턴스가 삭제되면 def __del__(self) 에 정의한 내용이 리턴됩니다.

 

Called when the instance is removed from the value table

 

ex) 함수가 사라지면 파일이 삭제될 때 사용되거나 할 때 사용됩니다.

def __del__(self):  # 아래 명령으로 인스턴스가 삭제될 때 호출 됩니다.

del homeAtSeoul  # homeAtSeoul이라는 인스턴스가 삭제된다.

 

Instance

댓글

💲 추천 글