面向对象编程实战
使用面向对象编程将图书管理系统进行改造
import os
class File:
name = 'books.txt'
def __init__(self):
file = open(File.name, 'a', encoding='utf-8')
file.close()
class Manage:
def add(self):
book = input('请您输入书名:')
with open(File.name, 'a', encoding='utf-8') as file:
file.write(book + '\n')
print(f'{book}增加成功!')
def delete(self):
book = input('请您输入需要删除的书名:')
file = open(File.name, 'r', encoding='utf-8')
books = file.readlines()
file.close()
if book + '\n' in books:
books.remove(book + '\n')
file = open(File.name, 'w', encoding='utf-8')
file.writelines(books)
file.close()
print(f'{book}删除成功!')
else:
print('您输入的书名不存在!')
def modify(self):
book = input('请您输入需要修改的书名:')
file = open(File.name, 'r', encoding='utf-8')
books = file.readlines()
file.close()
if book + '\n' in books:
newbook = input('请您输入新的书名:')
books[books.index(book + '\n')] = newbook + '\n'
file = open(File.name, 'w', encoding='utf-8')
file.writelines(books)
file.close()
print(f'{book}已修改为{newbook}!')
else:
print('您输入的书名不存在!')
def search(self):
size = os.path.getsize(File.name)
if size == 0:
print('目前没有图书!')
else:
with open('books.txt', 'r', encoding='utf-8') as file:
for book in file:
print(f'书名:{book}')
class Interface(Manage):
def main(self):
while True:
print('-' * 50)
print('欢迎使用图书管理系统!')
print('-' * 50)
print('增加图书【1】删除图书【2】修改图书【3】查看图书【4】')
print('-' * 50)
num = input('请输入数字指令:')
if num == '1':
self.add()
elif num == '2':
self.delete()
elif num == '3':
self.modify()
elif num == '4':
self.search()
else:
print('您的输入错误!')
file = File()
interface = Interface()
interface.main()