알파카징징이 알파카징징이 코딩하는 알파카

데이터 구조 및 분석 ch_1_10 Class and Instance

» writing

KAIST 산업및시스템공학과 문일철_ 데이터 구조 및 분석 수업을 참고하여 작성하였습니다

ch_1_10 Class and Instance

정의


Class and Instance

1. Class and Instance
: instantiation
설계도(class) -> 집 (instances)
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("Root color is ", self.colorRoof, \
              ", and Door color is ", self.stateDoor)
homeAtDaejeon = MyHome()
homeAtSeoul = MyHome()
homeAtSeoul.openDoor()
homeAtDaejeon.paintRoof('blue')
homeAtDaejeon.printStatus()
homeAtSeoul.printStatus()

# Root color is  blue , and Door color is  closed
# Root color is  red , and Door color is  open
2. Important Methods in Class (Constructor, Destructor)
: Some basic methods, or member functions in classes
- constructor : called when instantiated
---> def__init__(self, . . .) :
- deconstructor : called when the instance is removed from the value table
---> def __del__(self) :
from time import ctime

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("Root color is ", self.colorRoof, \
              ", and Door color is ", self.stateDoor)
    def __init__(self, strAddress):
        print('Built on', strAddress)
        print('Built at', ctime())
    def __del__(self):
        print('Destroyed at', ctime())

homeAtDaejeon = MyHome('Daejeon KAIST')
homeAtDaejeon.printStatus()
del homeAtDaejeon

# Built on Daejeon KAIST
# Built at Sun Jul  4 00:49:25 2021
# Root color is  red , and Door color is  closed
# Destroyed at Sun Jul  4 00:49:25 2021