Python 문법: 클래스, import, 타입, 예외

jjin·2024년 3월 20일
0

20240320

클래스

class Student(Person): # 상속
	def __init__(self, name):
    	self.name = name
        
    def study(self):
    	print(f"{self.name}이 공부중")
 
 s = Student(name="Jjin")
 s.study()
class Car:
	# 클래스 변수 (static: 인스턴스화 하지 않아도 사용)
	fuel=100
    
    # 클래스 메서드 (static)
	@classmethod
    def show_fuel(cls):
    	print(cls.fuel)
        
Car.show_fuel()
Car.fuel

모듈, 패키지

├── a # 패키지
│   ├── b.py
│   └── c.py
└── d.py

모듈: 변수, 함수 모은 파일
패키지: 모듈 모은 디렉토리

모듈을 패키지 내 다른 모듈에서 (모든 변수, 함수)사용 위해 import 파일명 (.py 떼고)

#c.py
import b

get_info()

패키지를 모듈에서 사용 위해 from ... import

#d.py
from a import b

get_info()

모듈의 특정 변수나 함수만 불러오기

#d.py
from a.b import get_info

get_info()

if name == "main":

파이썬 파일을 직접 실행할 때만 실행되는 구문.
import되었을 때는 실행되지 않음.

활용 사례: 모듈 테스트 코드 작성, CLI나 애플리케이션으로 직접 실행 시의 동작 정의

print("Hello")

if __name__ == "__main__":
	print("Bye")

"main": 직접 실행되었을 때만 name에 할당되는 값. 현재 파일이 프로그램의 시작점(main)임을 의미.

type 명시

동적 타입 언어. 내부적 타입 추론 :(

def hello(name: str) -> None:
	print(f"hello {name}")

def sum_nums(nums: list) -> int:
	return sum(nums)

typing 모듈: 자세한 타입 명시

from typing import List

class School:
	def set_names(self, names: List[str]) -> None:
    	self.names = names

	def set_schedule(self, schedule: Dict[str, str]) -> None:
    	self.schedule = schedule
        
school = School()
school.set_names(names=["Jjin, Jjap"])
school.set_schedule(schedule={
	"9:00-10:00", "수학"
})

컴파일 타임 오류x. 타입체크 위해 mypy 사용 가능

예외처리

raise: Exception 발생

raise Exception("에러 발생")

# Traceback (most recent call last):
#	File "<filename>", line 1, in <module>
# Exception: 에러 발생

try - except : Exception 캐치

try:
	print("Hi")
    raise Exception("에러 발생")
    print("Bye")
except Exception as e:
	print(e)
finally:
	print("Finished")
    
# Hi
# 에러 발생
# Finished
profile
진짜

0개의 댓글

관련 채용 정보