Tianhao Cui

It is about code, it is not about code

  • Home
  • Code
  • Apple
  • Others
All Blogs My Verse

Tianhao Cui

It is about code, it is not about code

  • Home
  • Code
  • Apple
  • Others

Python-OOP-2

2020-07-15

又有一段时间没更新了,历经艰难,终于回到祖国的怀抱了

前言

这一些日子没怎么写代码,感觉生疏了不少。万变不离其宗,代码这东西也是得反复练习,自己上手,才能越来越熟练阿。这遍文章不会很长,还是关于面向对象的一个巩固和练习。

练习程序

用面向对象的形式编写一个老师角色,并实现创建老师,查询老师,删除老师等要求

其实你去Baidu上一搜索,答案马上就会有。照猫画虎谁不会呢,但其实我们还真不能小瞧了照猫画虎的本事,谁一下子上来就会呢?谁不是从0开始的呢?

  1. 为什么会选择这个题呢?

    其实审完题,我就决定用这个程序练手了,因为题目很有实际性,且看起来稍微复杂一些

  2. 我是怎么开始的呢?

    上面提到了照猫画虎,我这次不会写,下次会写一点,再下次就可以从零开始了。

  3. 这是个什么程序?

    编写程序往往离不开对于数据的操纵,而这个程序对于数据的基本处理都涵盖了,包括(存储,增加,编辑,删除,和打印)当然从前面的文章也可以看出来,都是关于数据处理的。

  4. 展望

    我觉得这个程序的结构对于基础知识的运用非常有帮助,对于以后程序的编写有很大的借鉴作用。总的来说,对于初学者是一个很好的模版。

Code

main.py

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
27
import sys
import menu
from func import teachers
from func import schools

def main():
m = """
------- Management System ---------
1. Manage teachers
2. Manage schools
3. Quit
"""
print(m)
user=input(">>").strip()
if user=='1':
menu.interactive(teachers)
elif user=='2':
menu.interactive(schools)
elif user=='3':
sys.exit()
else:
return main()

if __name__ == '__main__':
main()
#menu.interactive(schools)
#main.interactive(teachers)

menu.py

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
27
28
29
30
31
32
33
34
35
36
37
38
def interactive(object):
menu = """
------- {obj}管理 ---------
1. 创建{obj}(功能已实现)
2. 查看{obj}(功能已实现)
3. 删除{obj}(功能已实现)
4. 查看{obj}列表
5. 退出
""" .format(obj=object.__name__)

menu_dict={
'1':'new',
'2':'catch',
'3':'remove',
'4':'output',
'5':'quit',
}
exit_flag=False
while not exit_flag:
print(menu)
user_option=input(">>").strip()
if user_option in menu_dict:
obj=object()
if user_option=='1':
getattr(obj,menu_dict.get(user_option))()
if user_option=='2'or user_option=='3':
obj.name = input('input {obj} name >'.format(obj=object.__name__))
getattr(obj,menu_dict.get(user_option))(obj)
if user_option=='4':
print('{0:*^30}'.format(object.__name__ + ' List'))
getattr(obj, menu_dict.get(user_option))(obj)
if user_option=='5':
print("quitting...")
exit_flag=True
else:
print("***************")
print("Invaild input!!")
exit_flag=True

manage.py

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import pickle
import os

class utility(object):
def __init__(self,file):
self.file=file

def dump(self,obj):
with open(self.file,'ab') as f:
pickle.dump(obj,f)

def loading(self):
if os.path.isfile(self.file):
with open(self.file,'rb') as f:
while True:
try:
obj=pickle.load(f)
yield obj
except:
break

def edit(self,obj):
old_file=utility(self.file+'.old')
for i in self.loading():
if i.name==obj.name:
old_file.dump(obj)
else:
old_file.dump(i)
os.remove(self.file)
os.rename(self.file+'.old',self.file)

def delete(self,obj):
old_file=utility(self.file+'.old')
for i in self.loading():
if i.name!=obj.name:
old_file.dump(i)
else:
print("Deleting....",obj.name)
os.remove(self.file)
os.rename(self.file+'.old',self.file)

func.py

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import os
from manage import utility
from setting import path

class manage(object):
path=''
def catch(self,obj):
c=utility(obj.path)
t=c.loading()
for i in t:
if i.name==obj.name:
print("Found!",i.__dict__)
return obj
else:
print("No result!")

def new(self,obj):
print(obj.path)
n=utility(obj.path)
if not self.catch(obj):
n.dump(obj)
print("Created!",obj.__dict__)
else:
print("Already existed!")

def remove(self,obj):
r=utility(obj.path)
r.delete(obj)
print("Deleted!",obj.__dict__)

def catch_all(self,obj):
a=utility(obj.path)
target=a.loading()
list=[]
for i in target:
list.append(i)
return list

def output(self,obj):
print_list=self.catch_all(obj)
for i in print_list:
print(i.__dict__)


class teachers(manage):
path=os.path.join(path,"teachers_obj")
def new(self):
self.name=input("Name:>>")
self.age=input("Age:>>")
manage().new(self)

class schools(manage):
path=os.path.join(path,"schools_obj")
def new(self):
self.name=input("Name:>>")
self.address=input("Address:>>")
manage().new(self)

setting.py

1
2
3
4
import os

path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'db')
#print(path)

#总结
整个程序看下来,我明白了以下几点

  1. 整个程序已manage.py下的utility类为基础实现了数据的存储,调用和删除。在func.py下又创建了一个manage父类和两个schools,teachers的子类,从而在utility上又增加了一层。所以整个程序主要是在这两个大类上进行函数的调用来实现题目要求,总体来说思路还是比较清晰的。

  2. 对比之前写的程序,每增加一个大类,都要再写一遍重复的关于这个类的数据调用,参见Day6,虽然当时也构造了Class,但是没有掌握面向对象的精髓所在,从上面的程序可知,当我们新增加了对象就没有必要再重复了,直接调用manage类里的函数就可以了,同理可证manage类,直接调用utility里的函数。

  3. 对于面向对象的掌握与熟练肯定不是短时间就能滚瓜烂熟的,还是需要充分的参考,借鉴和自己的上手。对于上面这么一个小程序就有很多东西可以挖掘和学习。运用OOP,要求很强的逻辑性和大局观,程序也要比面向过程精简了不少。

  • Code
  • Python

扫一扫,分享到微信

微信分享二维码
Blockchain-Python
MacOS-Big-Sur
© 2021 Tianhao Cui
Hexo Theme Yilia by Litten
  • All Blogs
  • My Verse

tag:

  • Code
  • Blockchain
  • Python
  • Others
  • Interview
  • Apple
  • MacOS
  • Algorithm
  • iPhone

    缺失模块。
    1、请确保node版本大于6.2
    2、在博客根目录(注意不是yilia根目录)执行以下命令:
    npm i hexo-generator-json-content --save

    3、在根目录_config.yml里添加配置:

      jsonContent:
        meta: false
        pages: false
        posts:
          title: true
          date: true
          path: true
          text: false
          raw: false
          content: false
          slug: false
          updated: false
          comments: false
          link: false
          permalink: false
          excerpt: false
          categories: false
          tags: true
    

And now these three remain:faith,hope,love
But the greatest of these is love