- # _*_ coding: utf-8 _*_
- class Student: #新的student类
- global operator #全局变量global
- def get(self, name, age, high, o): #接收用户的输入
- self.name=name
- self.age=age
- self.high=high
- self.o=o
- def show(self): #打印用户刚刚输入的数据
- ask=raw_input('Do you want to show them(y/n):') #询问
- if ask=='y' or ask=='Y':
- print '______________________________'
- print 'name:'+self.name
- print 'age:'+self.age
- print 'high:'+self.high
- print '______________________________'
- else:
- print'______________________________'
- print "data will not show"
- return True #只要用户没有选择退出,那么就返回一个True,保证程序继续运行
- def save(self): #保存用户输入的数据
- ask1=raw_input('Do you want to save them(y/n):') #询问
- if ask1=='y' or ask1=='Y':
- print'______________________________'
- f=file('D:\\students.txt','a') #在指定文件中添加数据
- f.write(name)
- f.write(' ')
- f.write(age)
- f.write(' ')
- f.write(high)
- f.write('\\n')
- f.close()
- print "... ... saving is over ... ..."
- else:
- print'______________________________'
- print "data will not save"
- return True #返回True
- def find(self): #寻找,并打印出用户需求数据的所在行
- ask3=raw_input('input the anything you want to find:') #询问
- f=file('D:\\students.txt') #指定文件
- while True:
- line=f.readline() #逐行读取,并判断数据是否存在此行
- if ask3 in line:
- print line
- continue
- if len(line)==0: #如果读取长度为零
- break #终止
- print 'over...'
- return True #返回True
- def showall(self): #打印所有的“已经保存”的数据
- ask4=raw_input('Do you want to show all(y/n):') #询问
- if ask4 =='y' or ask4 =='Y':
- f=file('D:\\students.txt')
- while True:
- line=f.readline()
- print line
- if len(line)==0: #如果长度为0,终止
- break
- return True #返回True
- def exit(self): #用户选择退出,重新输入数据
- return 0 #如果用户选择了exit 那么返还一个0 到do(self)函数
- operator = {'exit':exit, 'save':save, 'show':show, 'find':find, 'showall':showall} #定义字典,供用户选择指定方法
- def do(self): #接收用户的执行命令
- c=operator.get(self.o)(self) #从字典中选择对应的键值,调用指定函数,并接收函数返回值
- return c #将接收到的返回值返回到调用本函数的地方 a=s.do()
- ##############################################################
- print '*'*30
- a=True
- while True: #当成立,用户输入
- name=raw_input('please input your name:')
- age=raw_input('please input your age:')
- high=raw_input('please input your high:')
- a=True #用户重新输入后需要一些操作,a重新赋值,保证下个while循环成立
- while a==True:
- print a #验证a值
- o=raw_input('Input (save, show, find, showall, exit):') #询问获取用户的操作
- print '______________________________'
- s=Student()
- s.get(name, age, high, o) #将数据传入类中
- a=s.do() #接收返回的值
- #该片段来自于http://www.codesnippet.cn/detail/2608201410320.html
来源: http://www.codesnippet.cn/detail/2608201410320.html