클래스와 객체
자바의 Access modifier(접근 제어자) : public, private, protected
파이썬에선 이러한 용어는 없지만 개념은 존재한다.
_ 하나 짜리는 자바에서 protected와 같은 개념이다.
__ 는 클래스 밖에서 초기화가 불가능 하다. 자바에서 private 개념이다. 클래서 내에서 속성을 접근 해주기위해
@property annotation 을 사용한다.
In[24]에서 name 변수에 직접적으로 값을 주는 것같지만 setter 메소드가 호출된 것이다.
파이썬에서 상속
is a 관계이기 때문에 상속을 해주는데 자바에서 처럼 extend 해주는 것이 아니라 () 안에 클래스명을 넣어주면된다.
연산자 오버라이드
텍스트 파일 기반 사원정보 CRUD
# 파일에 이어쓰기 : w, r, a
# 키보드에서 사원정보를 입력받아서 Emp객체에 저장
# 텍스트 파일에 사원정보를 저장(id,name,dept,phone)
# 한행을 읽어서 Emp 객체를 생성
# 한행을 읽어오면서 수정대상 행이라면, 메모리에서 행을 수정/덮어쓰기
# 한행을 읽어오면서 삭제대상 행이라면, 메모리에 로드하지 않음/덮어쓰기
# 프로그램이 시작되면 아래와 같은 메뉴가 표시된다
# 추가(a), 목록(s), 검색(f), 수정(u), 삭제(d), 종료(x):
# 리스트에 포함된 객체의 정렬
# emp_list = sorted(emp_list, key=lambda e:e.id)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
class Emp:
def __init__(self, id=None,name=None,dept=None,phone=None):
self.id=id
self.name=name
self.dept=dept
self.phone=phone
def __str__(self):
return '%s\t%s\t%s\t%s' %(self.id,self.name,self.dept,self.phone)
def __eq__(self, other):
return self.id==other.id
def get_line(self):
return '%s %s %s %s'%(self.id,self.name,self.dept,self.phone)
def set_line(self, line):
sp_list = line.strip().split()
if len(sp_list)<4:
print('유효하지 않은 데이터입니다')
return
id,name,dept,phone = sp_list
self.id = id
self.name = name
self.dept = dept
self.phone= phone
|
cs |
1
2
3
4
5
6
7
|
def menu():
m = "추가(a), 목록(s), 검색(f), 수정(u), 삭제(d), 종료(x):"
m_in = input(m).strip()
if len(m_in)!=1:
print('메뉴입력 오류')
return None
return m_in
|
cs |
1
2
3
4
5
6
7
|
def input_emp():
in_list = input('id name dept phone:').strip().split()
if len(in_list)<4:
print('유효하지 않은 정보 입력')
return None
id,name,dept,phone = in_list
return Emp(id,name,dept,phone)
|
cs |
1
2
3
4
5
|
def write_emp(emp):
fout = open('C:/Users/parkj/1Python_Projects/text/file_emp_crud.txt', 'a')
fout.write(emp.get_line()+'\n')
fout.close()
return True
|
cs |
1
2
3
|
def add():
emp = input_emp()
return write_emp(emp)
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
|
def find():
uid = input('검색할 사원의 id:').strip()
key_emp = Emp(id=uid)
fin = open('C:/Users/parkj/1Python_Projects/text/file_emp_crud.txt', 'r')
for line in fin.readlines():
emp = Emp()
emp.set_line(line)
if emp==key_emp:
print(emp)
return True
fin.close()
return False
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
|
def load_list():
fin = open('C:/Users/parkj/1Python_Projects/text/file_emp_crud.txt', 'r')
line_list = fin.readlines()
fin.close()
emp_list = []
for line in line_list:
e = Emp()
e.set_line(line)
emp_list.append(e)
emp_list = sorted(emp_list, key=lambda e:e.id)
return emp_list
|
cs |
1
2
3
4
5
|
def print_list():
emp_list = load_list()
print()
for emp in emp_list:
print(emp)
|
cs |
1
2
3
4
5
6
|
def overwrite(emp_list):
fout = open('C:/Users/parkj/1Python_Projects/text/file_emp_crud.txt', 'w')
for emp in emp_list:
fout.write(emp.get_line()+'\n')
fout.close()
return True
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
def update():
up_info = input('수정할 사원정보(id phone):').strip()
up_list = up_info.split()
if len(up_list)<2:
print('유효하지 않은 정보 입력')
return False
id, phone = up_list
up_emp = Emp(id=id, phone=phone)
emp_list = load_list();
if up_emp in emp_list:
idx = emp_list.index(up_emp)
emp_list[idx].phone = phone
overwrite(emp_list)
print('수정성공')
return True
print('수정실패')
return False
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
def delete():
del_info = input('삭제할 사원정보(id):').strip()
if len(del_info)==0:
print('유효하지 않은 정보 입력')
return False
id = del_info
del_emp = Emp(id=id)
emp_list = load_list();
if del_emp in emp_list:
emp_list.remove(del_emp)
overwrite(emp_list)
print('삭제성공')
return True
print('삭제실패')
return False
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
while True:
m_in = menu()
if m_in == 'a':
add()
elif m_in =='s':
print_list()
elif m_in =='f':
find()
elif m_in =='u':
update()
elif m_in =='d':
delete()
elif m_in =='x':
break
else:
print("메뉴입력 오류")
print('프로그램 종료')
|
cs |
실행결과 :

'Python programming' 카테고리의 다른 글
(23.02.09.)Python 프로그래밍: Web Crawling, Web Scraping, BeautifulSoup (0) | 2023.02.14 |
---|---|
(23.02.08)Python 프로그래밍 : Pickle 모듈을 사용한 직렬화(Serialization), 예외처리 (0) | 2023.02.14 |
(23.02.06.)Python 프로그래밍 : module sys , 파이썬 Class 와 객체 (0) | 2023.02.07 |
(23.02.03)Python 프로그래밍: 파이썬 함수 실습 (0) | 2023.02.06 |
(23.02.02.)Python 프로그래밍: 파이썬 Set(집합) 다루기 & 파이썬 연산자 (0) | 2023.02.06 |
댓글