251010 TIL
2025. 10. 10. 17:52ㆍCourses/아이티윌 오라클 DBA 과정
상속
"""
클래스 상속 inheritance
- 재활용
- 부모와 자식, 조상과 후손(파생), super와 sub
- 클래스가 가지고 있는 멤버나 메소드를 상속받는 클래스가 모두 사용
- 형식) class 자식클래스(부모클래스)
"""
class AA:
def one(self):
print("AA.one()...")
def two(self):
print("BB.two()...")
class BB(AA):
pass
aa = AA()
aa.one()
aa.two()
bb = BB()
bb.one()
bb.two()
class CC(AA):
def three(self):
print("CC.three()")
class DD(CC):
def four(self):
print("DD.four()...")
cc = CC()
cc.one()
cc.two()
cc.three()
dd = DD()
dd.one()
dd.two()
dd.three()
dd.four()
##########################################################################
# 2. 다중 상속
# -> 형식) class 자식클래스(부모클래스, 부모클래스)
class Plus:
def hap(self, a, b):
return a + b
class Subs:
def minus(self, a, b):
return a - b
class Calc(Plus, Subs):
pass
calc = Calc()
print(calc.hap(3, 4)) # 7
print(calc.minus(3, 4)) # -1
##########################################################################
# 3. 오버라이딩(Overriding)
"""
- 상속받은 부모 클래스의 메서드를 자식 클래스에서 재정의해서 사용하는 것
- 부모 클래스에 이미 정의된 메서드가 있음
- 자식 클래스에서 같은 이름의 메서드를 다시 정의하면 부모의 메서드 대신 자식 클래스의 메서드가 실행됨
"""
class Korea:
name = "코리아"
def view(self):
print("Korea.view()...")
def disp(self):
print("Korea.disp()..." + self.name)
class Seoul(Korea):
name = "서울특별시"
def disp(self):
print("Seoul.disp()..." + self.name)
se = Seoul()
se.view()
se.disp()
##########################################################################
# 4. super()
# -> 부모클래스에서 사용된 함수의 코드를 받아서, 자식클래스에서 재사용시 사용
class Phone:
name = None
# 생성자 함수 Constructor
def __init__(self, name=None):
self.name = name
print("{} phone {} 개통".format(self.name, 123))
def calling(self):
print("---", self.name)
print("phone dial selected")
ph = Phone("kim")
ph.calling()
class CameraPhone(Phone):
def __init__(self, name=None):
super().__init__(name)
def camera(self):
print("===", self.name)
print("camera selected")
cam = CameraPhone("lee")
cam.calling()
cam.camera()
##########################################################################
# 5. overloading
# -> 같은 이름의 메소드(함수) 를 매개변수의 개수나 타입에 따라 다르게 동작하도록 정의하는 것
# -> 기본적으로 메소드 오버로딩을 지원하지 않음
class Compute:
def hap(self, a):
return a
def hap(self, a, b):
return a + b
def hap(self, a, b, c):
return a + b + c
예외처리
"""
- 프로그램이 실행 중 오류가 발생했을때 -> 예외상황
- 예외상황이 발생하면 코드 진행이 중단되므로 계속 진행할 수 있도록 선언
- Exception이 발생하더라도 정상적으로 프로그램은 종료시킬 수 있다
- 형식) try:
문제가 없을 시 실행할 코드
except:
문제 발생(예외상황)시 실행할 코드
"""
# 1. 예외처리 하지 않은 경우
"""
print("START")
print(1)
print(3 / 0) # ZeroDivisionError: division by zero
print(5)
print("END")
"""
# 2. 예외처리를 한 경우
print("START")
try:
print(1)
print(3 / 0) # ZeroDivisionError: division by zero
print(5)
except Exception as e:
print(f"예외발생: {e}")
print("END")
# 3. try except else
# -> except가 발생하지 않으면 else 실행
print("START")
try:
print(1)
result = 3
print(5)
except Exception as e:
print(f"예외발생: {e}")
else:
print(f"result: {result}")
print("END")
# 4. try except finally
# -> except 발생 유무와 상관없이 finally 구문 실행
print("START")
try:
print(1)
result = 3 / 0
print(5)
except Exception as e:
print(f"예외발생: {e}")
else:
print(f"result: {result}")
finally:
print("연산종료")
print("END")
pip
# pip 명령어 : 파이썬 확장 모듈을 설치, 삭제할 수 있는 기능 제공
"""
>python --version 파이선 버전 확인
>python -m pip install --upgrade pip pip명령 업그레이드
>pip list 파이선 모듈 및 패키지 목록 확인
>pip freeze
>pip install 모듈명 파이선 모듈 설치
>pip install 모듈명==버전 원하는 버전으로 모듈 설치
>pip uninstall -y 모듈명 파이선 모듈 삭제
>pip install numpy numpy 모듈 설치
>pip install wordcloud wordcloud 모듈 설치
>pip uninstall -y wordcloud wordcloud 모듈 삭제
"""
모듈
상수, 함수가 정의된 모듈
my_module.py
## 1)
NAME = "Hello Python"
def plus(a, b):
return a + b
def minus(a, b):
return a - b
# 모듈(module)의 활용
# -> 모듈:다른 프로그램에서 활용하기 위한 프로그램 조각, 남이 만들어둔 코드의 집합
# -> 하나의 파이썬 .py 파일이 하나의 모듈이 된다
# -> 모듈 선언 형식) import 파일이름 또는 모듈이름
# 모듈 파일 my_module.py
## 1) 모듈 import
import my_module
print(my_module.NAME) # Hello Python
print(my_module.plus(1, 3)) # 4
print(my_module.minus(2, 4)) # -2
## 2) 별칭
import my_module as mm
print(mm.NAME) # Hello Python
print(mm.plus(1, 3)) # 4
print(mm.minus(2, 4)) # -2
## 3) 특정 기능만 가져오기
from my_module import NAME
from my_module import plus
print(NAME) # Hello Python
print(plus(5, 3)) # 8
# print(minus(5, 3)) # NameError: name 'minus' is not defined
클래스가 정의된 모듈
my_module.py
## 2)
class Member:
uname = None
email = None
def __init__(self, uname, email):
print("Member 클래스 생성자 호출됨...")
self.uname = uname
self.email = email
def disp(self):
style = "이름 : {0} / 이메일 : {1}"
print(style.format(self.uname, self.email))
# 클래스가 정의된 모듈 참조하기
# 모듈 파일 my_module.py 작성
## 1)
import my_module
mem = my_module.Member("kim", "kim@itwill.com") # Member 클래스 생성자 호출됨...
mem.disp() # 이름 : kim / 이메일 : kim@itwill.com
## 2) 별칭 적용
import my_module as mm
mem = mm.Member("lee", "lee@itwill.com") # Member 클래스 생성자 호출됨...
mem.disp() # 이름 : lee / 이메일 : lee@itwill.com
## 3) 특정 클래스만 가져오기
from my_module import Member
mem = Member("park", "park@itwill.com") # Member 클래스 생성자 호출됨...
mem.disp() # 이름 : park / 이메일 : park@itwill.com
객체가 정의된 모듈
my_module.py
## 3)
class Calc:
def plus(self, a, b):
return a + b
def minus(self, a, b):
return a - b
mycalc = Calc() # 자체적으로 객체를 생성하는 모듈
# 객체가 정의된 모듈 참조
# 모듈 파일 my_module.py 작성
## 1)
import my_module
print(my_module.mycalc.plus(3, 2)) # 5
print(my_module.mycalc.minus(3, 2)) # 1
## 2) 모듈 자체에 별칭 부여
import my_module as mm
print(mm.mycalc.plus(3, 2)) # 5
print(mm.mycalc.minus(3, 2)) # 1
## 3) 모듈에 정의된 특정 객체만 가져오기
from my_module import mycalc
print(mycalc.plus(3, 2)) # 5
print(mycalc.minus(3, 2)) # 1
파일 입출력
텍스트 파일
# 파일 입출력
# -> r : 읽기모드
# -> w : 쓰기 모드(overwrite 덮어쓰기)
# -> a : 추가 모드(append 추가)
# 1) 파일 쓰기
# -> 대상 파일이 없으면 생성(create)
f = open("./section1010/helloworld.txt", "w", encoding="utf-8")
f.write("Hello Python!!\n\n")
f.write("안녕하세요~~ 파이썬!!\n")
f.close()
print("helloworld.txt 완성!!!")
########################################################################
# 2) 파일 읽기
# -> 대상 파일이 존재하지 않으면 에러 발생
# f = open("./section1010/hello.txt", "r", encoding="utf-8") # FileNotFoundError: [Errno 2] No such file or directory: './section1010/hello.txt'
f = open("./section1010/helloworld.txt", "r", encoding="utf-8")
print(f.read())
# End Of File(EOF) : 파일의 끝
f.close()
########################################################################
# 3) 추가 모드로 파일 객체 생성
with open("./section1010/helloworld.txt", "a", encoding="utf-8") as f:
for i in range(1, 10):
f.write("%d >> " % i)
f.write("Life is too short,")
f.write("you need Python\n")
print("helloworld.txt 완성!!!")
########################################################################
# 4) 읽기 모드로 파일 객체 생성하기
with open("./section1010/helloworld.txt", "r", encoding="utf-8") as f:
# data = f.read() # 파일의 끝(EOF)을 만날 때까지 한 글자씩 가져오기
# print(data)
while True:
line = f.readline() # 엔터를 기준으로 가져오기
if not line:
break
print(line.strip())
helloworld.txt
Hello Python!!
안녕하세요~~ 파이썬!!
1 >> Life is too short,you need Python
2 >> Life is too short,you need Python
3 >> Life is too short,you need Python
4 >> Life is too short,you need Python
5 >> Life is too short,you need Python
6 >> Life is too short,you need Python
7 >> Life is too short,you need Python
8 >> Life is too short,you need Python
9 >> Life is too short,you need Python
CSV
# .csv: 데이터가 , 기호를 기준으로 구성된 파일
grade = [
{"name": "홍길동", "kor": 90, "eng": 85, "mat": 100},
{"name": "무궁화", "kor": 30, "eng": 80, "mat": 90},
{"name": "라일락", "kor": 60, "eng": 55, "mat": 70},
]
style = "{0}, {1}, {2}, {3}\n"
# 1) CSV 파일 쓰기
with open("./section1010/grade.csv", "w", encoding="utf-8") as f:
for g in grade:
f.write(style.format(g["name"], g["kor"], g["eng"], g["mat"]))
print("grade.csv 파일 완성!!")
# 2) CSV 파일 읽기
with open("./section1010/grade.csv", "r", encoding="utf-8") as f:
data = f.readlines()
for i in data:
std = i.strip().split(",")
name = std[0]
kor = int(std[1])
eng = int(std[2])
mat = int(std[3])
total = kor + eng + mat
avg = total / 3
print(f"{name} {kor} {eng} {mat} {total} {avg:.2f}")
grade.csv
홍길동, 90, 85, 100
무궁화, 30, 80, 90
라일락, 60, 55, 70'Courses > 아이티윌 오라클 DBA 과정' 카테고리의 다른 글
| 251014 TIL (0) | 2025.10.14 |
|---|---|
| 251013 TIL (0) | 2025.10.13 |
| 251002 TIL (0) | 2025.10.02 |
| 251001 TIL (0) | 2025.10.01 |
| 250930 TIL (0) | 2025.09.30 |