Python 클래스 기초 (1)
2025. 7. 30. 14:41ㆍ심화_인공지능 YOLO기반 부트캠프_일기(CNN)
📌 오늘의 주제
오늘은 Python에서 객체지향 프로그래밍의 기본이 되는 클래스 개념과,
CSV/JSON 파일을 활용한 데이터 저장/불러오기 실습을 진행했다.
🔸 클래스의 기초 - 은행 계좌 만들기
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self.balance
def withdraw(self, amount):
if amount > self.balance:
return "잔액 부족"
self.balance -= amount
return self.balance
- 위 코드는 간단한 은행 계좌 클래스
- deposit(), withdraw()는 입출금을 처리하는 메서드
- __init__()은 생성자. 인스턴스를 만들 때 자동 호출된다
account = BankAccount("홍길동", 1000)
print(account.deposit(500)) # 1500
print(account.withdraw(200)) # 1300
👉 객체지향이 처음에는 어렵지만, 클래스 안에 데이터와 기능을 함께 담는 구조라고 이해하면 좀 더 명확해진다.
🔸 클래스 상속
# ------------------------------------------------------
# 상속시에 자식 클래스에서 부모 클래스의 속성을 초기화하는 예
# ------------------------------------------------------
class Parent:
def __init__(self, name):
self.name = name
print(f"Parent 생성자 호출: name = {self.name}")
class Child(Parent):
def __init__(self, name, age):
super().__init__(name)
self.age = age
# super()는 self를 랩핑하여 기능확장하여 부모 클래스의 메소드 호출 가능하도록 한 Proxy 오브젝트
print(f"Child 생성자 호출: age = {self.age}")
# 테스트
child = Child("홍길동", 20)
- super()는 부모 클래스의 기능을 호출할 수 있게 해주는 함수
- 자식 클래스에서 부모 생성자를 호출하면서 확장 가능
🔸 CSV & JSON 다루기
✅ CSV 파일 저장 & 읽기
# ------------------------------------------------------
# CSV, JSON 파일 실전
# Comma Separated Value, Javascript Standard Object Notation
# ------------------------------------------------------
import csv
import json
# CSV 저장
data = [["이름", "나이"], ["홍길동", 30], ["김영희", 25]]
file_path = "/content/drive/MyDrive/Python_AI/YOLO/Codes/Python Advanced/"
with open(file_path+"people.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerows(data)
# CSV 읽기
with open(file_path+"people.csv", newline='', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
name, age = row # unpack
print(f"{name}\t{age}") # f-string
#print("{}\t{}".format(name,age)) # format()
#print("%s\t%s"%(name,age)) # %s
- 리스트 데이터를 CSV 형식으로 저장
- 줄바꿈 문제 방지를 위해 newline=''을 꼭 넣어야 함
python
복사편집
with open("people.csv", newline='', encoding='utf-8') as csvfile: reader = csv.reader(csvfile) for row in reader: print(row)
✅ JSON 저장 & 읽기
# JSON 저장
person = {"name": "홍길동", "age": 30, "email": "hong@example.com"}
with open("person.json", "w", encoding="utf-8") as f:
json.dump(person, f, ensure_ascii=False, indent=2)
# JSON 읽기
with open("person.json", "r", encoding="utf-8") as f:
person_data = json.load(f)
print(person_data)
[2일차] Python 클래스 기초 (1)에서 계속...
'심화_인공지능 YOLO기반 부트캠프_일기(CNN)' 카테고리의 다른 글
| Pandas : 데이터프레임 기초부터 병합·결측치 처리·시각화까지 (12) | 2025.08.13 |
|---|---|
| 파이썬 고급 문법 정리 — 예외 처리, 제너레이터, 데코레이터까지,__call__ 메서드, 가변인자 덧셈 (6) | 2025.08.12 |
| Python 클래스 기초 (2) (6) | 2025.07.30 |
| YOLO 소개와 Python 개발환경 준비 (4) | 2025.07.30 |
| 🧠 YOLO 기반 CNN 인공지능 부트캠프 프롤로그 (8) | 2025.07.30 |