데이터/Python

[파이썬] 클래스 사용하기

성장하기 2023. 6. 18. 18:47

절차 지향 vs 객체 지향

  • 객체 지향 프로그래밍(OOP)의 장점 : 코드의 재사용, 코드 중복 방지, 유지보수의 편의성, 대형 프로젝트 시 활용성이 좋음
  • 기존 방식(함수 중심) : 규모가 큰 프로젝트의 경우 → 데이터가 방대, 복잡해져 유지 보수가 어려워짐
    • 클래스 중심으로 진화 → 데이터 중심 → 객체로써 관리
  • 절차지향 vs 객체지향 어떤 것을 선택해야 하는가?
    • 간단한 프로그램(크롤링 등) → 절차 지향
    • 배포 목적, 지속적인 프로그램 → 객체 지향

일반적인 코딩

- 일반적인 코딩으로 데이터를 저장하는 경우 아래와 같다.

# 차량 1
car_company_1 = 'Ferrari'
car_datail_1 = [
	{'color': 'White'},
	{'housepower': 400},
	{'price': 8000}
]

# 차량 2
car_company_2 = 'BMW'
car_datail_2 = [
	{'color': 'Black'},
	{'housepower': 270},
	{'price': 5000}
]

# 차량 3
car_company_3 = 'Audi'
car_datail_3 = [
	{'color': 'Silver'},
	{'housepower': 300},
	{'price': 6000}
]

리스트 구조

- 리스트 구조로 데이터를 저장하는 경우 아래와 같으며, del 메서드로 데이터 값을 삭제할 수 있다.

car_company_list = ['Ferrari', 'BMW', 'Audi']
car_detail_list = [
	{'color': 'White','housepower': 400, 'price': 8000},
	{'color': 'Black', 'housepower': 270, 'price': 5000},
	{'color': 'Silver', 'housepower': 300, 'price': 6000}
]

del car_company_list[1]
del car_detail_list[1]

print(car_company_list)
print(car_detail_list)

딕셔너리 구조

car_dicts = [
	{'car_company': 'Ferrari', 'car_detail': {'color': 'White','housepower': 400, 'price': 8000}},
	{'car_company': 'BMW', 'car_detail': {'color': 'Black', 'housepower': 270, 'price': 5000}},
	{'car_company': 'Audi', 'car_detail': {'color': 'Silver', 'housepower': 300, 'price': 6000}},
]

del car_dicts[1]
print(car_dicts)

 

클래스 구조

class Car():
	def __init__(self, company, details):
		self._company = company
		self._details = details
		
	def __str__(self): # 매직 메소드 (프린트 문 사용)
		return 'str : {} - {}'.format(self._company, self._details)
	

	def __repr__(self): # representation : str 메서드가 없는 경우에만 repr이 수행됨
		return 'repr : {} - {}'.format(self._company, self._details)

car1 = Car('Ferrari', {'color': 'White','housepower': 400, 'price': 8000})
car2 = Car('BMW', {'color': 'Black', 'housepower': 270, 'price': 5000})
car3= Car('Audi', {'color': 'Silver', 'housepower': 300, 'price': 6000})

# 리스트 선언
car_list = []

car_list.append(car1)
car_list.append(car2)
car_list.append(car3)
print(car_list) # 리스트 안에 객체로써 있을 때는 repr이 호출됨

for x in car_list:
	print(x)
  • __init__ : 생성자
  • __str__ : 매직 메소드, 프린트문으로 인스턴스 찍으면 이 메소드의 return값이 출력됨
  • __repr__ : str과 유사한 역할을 하나, 엔지니어 레벨에서 엄격하게 사용됨 (리스트 안에 객체로써 있을 때는 repr이 호출됨

클래스 작성

class Car():
	"""
	Car class
	Author : Lee
	date : 2023. 1. 23.
	사용법 : 자동차 회사 저장
	"""
	def __init__(self, company, details):
		self._company = company
		self._details = details
	
	def __str__(self):
		return 'str : {} - {}'.format(self._company, self._details)
	
	def __repr__(self):
		return 'repr : {} - {}'.format(self._company, self._details)
	
	def detail_info(self):
		print('Current ID : {}'.format(id(self)))
		print('Car Detail Info : {} {}'.format(self._company, self._details.get('price')))
  • dir(인스턴스) : 클래스의 모든 메타정보 반환
  • 인스턴스.__dict__ : 클래스 안을 들어다 보기 위한 속성, 내가 작성한 모든 정보를 보여준다
  • 인스턴스.__doc__ : 클래스의 주석을 볼 수 있음. → 주석을 작성해야하는 이유
  • 인스턴스의 id값은 다르며 클래스의 id값은 같다

 

클래스 변수

  • 모든 인스턴스가 공유
  • car1.__dict__ 와 같이 인스턴스의 name space에는 클래스 변수가 잡히지 않음
  • dir(car1) 에서는 클래스 변수 까지 확인 가능
  • 클래스 변수 접근
    • 인스턴스, 클래스 둘 다에서 접근 가능하다
    print(car1.car_count)
    print(Car.car_count)
    
  • 삭제 확인 del car2 로 삭제한 후 클래스 변수를 확인하면 감소됨을 확인 가능
  • 클래스 변수 확인
    • 인스턴스의 속성이 호출되면 인스턴스 네임스페이스에서 먼저 검색 후 없는 경우 상위 클래스 변수에서 검색해서 반환함
    • 그러나, 헷갈리기 때문에 인스턴스 변수에는 앞에 언더바(_)를 붙여 주는 등 구분해서 사용할 필요
class Car():
	"""
	Car class
	Author : Lee
	date : 2023. 1. 23.
	사용법 : 자동차 회사 저장
	"""
	
	# 클래스 변수 선언 (모든 인스턴스가 공유한다)
	# 클래스 변수는 __init__ 메서드와 doc 사이에 작성
	car_count = 0
	
	def __init__(self, company, details):
		self._company = company # 클래스 변수와 구분하기 위해 인스턴스의 속성 앞 언더바(_)를 붙임
		self._details = details
		Car.car_count +=1
	
	def __str__(self):
		return 'str : {} - {}'.format(self._company, self._details)
	
	def __repr__(self):
		return 'repr : {} - {}'.format(self._company, self._details)
	
	def __del__(self):
		Car.car_count -= 1
	
	def detail_info(self):
		print('Current ID : {}'.format(id(self)))
		print('Car Detail Info : {} {}'.format(self._company, self._details.get('price')))

 

---

본 게시글은 인프런 우리를 위한 프로그래밍 : 파이썬 중급 강의의 일부를 정리한 글 입니다.

 

https://www.inflearn.com/course/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D-%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EC%A4%91%EA%B8%89-%EC%9D%B8%ED%94%84%EB%9F%B0-%EC%98%A4%EB%A6%AC%EC%A7%80%EB%84%90/dashboard