데이터 구조 및 분석 ch_1_11 Module and Import
Jul 4, 2021
»
writing
KAIST 산업및시스템공학과 문일철_ 데이터 구조 및 분석 수업을 참고하여 작성하였습니다
ch_1_11 Module and Import
Module and Import
1. Module and Import : See how to separate the source code files - just put your code in another file (filename.py) : See how to use classes in other files - import filename : Use from to specify the directory, or the folder, path
# Home.py
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())
# UsingMyHome.py
import main
homeAtDaejeon = main.MyHome('Daejeon KAIST')
homeAtDaejeon.printStatus()
# Built on Daejeon KAIST -> constructor
# Built at Sun Jul 4 00:49:25 2021 -> constructor
# Root color is red , and Door color is closed -> printStatus()
# Destroyed at Sun Jul 4 00:49:25 2021 -> deconstructor
2. Organizing Modules by Package : Directory or folder - Modules -> filename.py : call these directories as package : previous information is exactly (from package import module) : package has - __init__.py in the directory - how to difeerentiate between the ordinary and the package directories
from edu.kaist.session.edu.week1 import Home
3. Sample Program : Interaction with your program
class CashierLine :
lstLine = [] # member variable (list_
def addCustomer(self, strName): #member func
self.lstLine.append(strName)
def processCustomer(self):
strReturnName = self.lstLine[0]
self.lstLine.remove(strReturnName)
return strReturnName
def printStatus(self):
strReturn = ""
for itr in range(len(self.lstLine)) :
strReturn += self.lstLine[itr] + " "
return strReturn
binLoop = True
line = CashierLine()
while binLoop:
strName = input("Enter customer name : ")
if strName == ".":
break
elif strName == "->":
print("Processed : ", line.processCustomer())
print("Line : ", line.printStatus())
else :
line.addCustomer(strName)
print("Line :", line.printStatus())
print("Number of remaining custormers : ", len(line.lstLine))
# Enter customer name : Mooon
# Line : Mooon
# Enter customer name : Sun
# Line : Mooon Sun
# Enter customer name : ->
# Processed : Mooon
# Line : Sun
# Enter customer name : .
# Number of remaining custormers : 1