import를 활용하여 모듈을 임포트할 수 있고 as 키워드를 이용해서 이름을 단축시킬 수 있음
import calculator as cal # 임의로 정한 모듈
cal.add(10, 20)
cal.sub(10, 20)
from ~ import를 활용하여 모듈의 특정 기능만 사용할 수 있음
__name__ 전역변수__name__ 에는 모듈 이름이 저장되거나 '__main__'이 저장됨
이 때 실행파일인 경우에 '__main__'이 저장되고, 실행파일이 아닌 모듈의 경우 그 모듈의 파일 이름이 저장됨
import itertools
print(itertools.__name__) # itertools
print(__name__) # __main__
if __name__ == '__main__':은 이 파일이 실행 파일일 때만 아래 실행문을 실행하라는 의미임
site-packages에 있는 모듈은 어디서나 사용할 수 있음site-packages라는 디렉토리 내로 옮겨주면 됨venv/lib/site-packagesmath: 수학 관련 모듈random: 난수 관련 모듈time: 시간 관련 모듈자주 쓰는 수학관련 함수
sum()max(), min()pow()round()math 모듈의 함수
fabs()ceil()floor()trunc()gcd()factorial()sqrt()lt = time.localtime()lt.tm_yearlt.tm_monlt.tm_mdaylt.tm_hourlt.tm_minlt.tm_seclt.tm_wdayclass 키워드와 속성(변수) 그리고 기능(함수)를 이용해서 만듦
class Car: # 클래스 선언
def __init__(self, color, length): # 생성자
self.color = color # 속성
self.length = length
def doStop(self): # 기능
print('STOP!')
def doStart(self):
print('START!')
클래스 명의 첫글자는 대문자
객체는 클래스의 생성자를 호출함
car1 = Car('red', 200)
car2 = Car('blue', 300)
class NewGenerationPC:
def __init__(self, name, cpu, memory, ssd):
self.name = name
self.cpu = cpu
self.memory = memory
self.ssd = ssd
def doExcel(self):
print('excel run!')
def doPhotoshop(self):
print('photoshop run!')
def printPCInfo(self):
print(f'self.name: {self.name}')
print(f'self.cpu: {self.cpu}')
print(f'self.memory: {self.memory}')
print(f'self.ssd: {self.ssd}')
myPC = NewGenrationPC('myPc', 'i5', '16G', '256G')
myPC.printPCInfo()
myPC.cpu = 'i9'
myPC.memory = '64G'
myPC.printPCInfo()
copy()를 사용extend(), for문, copy(), [:] 등을 활용하여 깊은복사 가능클래스는 또 다른 클래스를 상속해서 내 것처럼 사용 가능
class NormalCar:
pass
class TurboCar(NormalCar): # TruboCar 클래스는 NormalCar 클래스를 상속
pass
__init__()가 자동으로 호출됨__init__()super()하위클래스에서 상위클래스의 메서드를 재정의(override)하는 것
class Robot:
def __init__(self, c, h, w):
pass
def fire(self):
print('총알 발사!')
class NewRobot(Robot):
def __init__(self):
super().__init__(c, h, w)
def fire(self):
print('불꽃 발사!') # 오버라이딩
상위 클래스에서 하위 클래스에 메서드 구현을 강요하는 것
하위클래스에서 지정하지 않을 시 에러 발생
하위클래스에서 반드시 구체화해야 하는 메서드는 상위클래스에 @abstractmethod(추상메서드) 데코레이터로 지정되어있음
추상메서드로 지정되지 않은 것은 반드시 구체화할 필요는 없지만, 추상메서드를 구체화하지 않은 경우 에러가 발생
추상클래스는 metaclass=ABCMeta 옵션을 주어 지정할 수 있음
from abc import ABCMeta, abstractmethod
# 1. 추상클래스 내에 정의된 추상 메서드가 없는 경우
class Airplane(metaclass=ABCMeta):
def backward(self):
print('후진!')
basicAirplane = Airplane()
basicAirplane.backward() # 후진!
# 2. 추상클래스 내에 정의된 추상 메서드가 있는 경우
class Airplane(metaclass=ABCMeta):
@abstractmethod
def forward(self): # 추상메서드
print('전진!')
def backward(self):
print('후진!')
basicAirplane = Airplane() # TypeError: Can't instantiate abstract class Airplane with abstract method forward
basicAirplane.backward()
Exception 클래스를 상속ArithmeticError, ZeroDivisionError, EnvironmentError, LookupError, SyntaxError 등등