我做的是一个很简单的Atm系统,很多都没约束条件

目的:

  • 用面向对象思维来处理
  • 运用文件的读写
    文件的读写用pickle模块和json模块来处理

pickle模块:

  • pickle模块处理数据功能很强大,但是弊端不同版本的python解释器不兼容
    pickle模块功能:
  • pickle.dumps(obj) 功能:将指定的对象序列化
  • pickle.dump(obj,f) 功能:将指定的对象序列化并写入到打开的文件中
  • pickle.loads(f2.read()) 功能:将二进制的字符串反序列化为对象
  • pickle.load(f2) 功能:读取打开的文件对象,并且将读取到的内容反序列化为对象

json模块的功能:

  • json模块处理数据也强大,但是需要自定义方法来进行数据的转换。(python的特殊数据类型)
  • json可以直接序列化python基本数据类型。
  • json.dumps(obj,default) 注意:若obj为python基本数据类型,我们无需写default,直 接进行序列化
    若obj为自定义的数据类型,这时候default后面跟的是将对象转为基本数据类型的函数
    功能:将obj使用default函数转为字典并且序列化为json字符串,并且返回
  • json.dump(obj,f,default) 功能:将obj使用default函数转为字典并且序列化为json字符串,
    并且写入到指定的打开的f中。
  • json.loads(jsonstr,object_hook)
    功能:将jsonstr转为字典,通过object_hook的方法将字典转为对象
  • json.load(f,object_hook) 功能:读取打开文件的内容,并且将读取的内容转为字典,
    通过object_hook的方法将字典转为对象。 本系统用了pickle模块也用了json模块

我的写的数据类型是 dict = { “卡号”:对象数据类型}
下面是pickle模块来读写:

#读
         try:
            with open("user.txt","rb") as f:
                 ATM.userDict = pickle.load(f)
         except:
             pass
         #写
         with open("user.txt","wb") as f1:
             pickle.dump(ATM.userDict,f1)

下面用json模块来读写

def aa1dict(a): 
    a_a = {"name":a.name,"idcard":a.idcard,"phonenum":a.phonenum,"cardnum":a.card.cardnum,"psd":a.card.password,"mon":a.card.money,"islock":a.card.islock}
    return a_a
#
def dictaa(d):
    a_aa = Card(d["cardnum"],d["psd"],d["mon"],d["islock"])
    a_b = User(d["name"],d["idcard"],d["phonenum"],a_aa)
    return a_b

#读
    try:
        with open("xxx.txt", "r", encoding="utf-8") as f:
            for line in f.readlines():
                obj = json.loads(line, object_hook=dictaa)
                ATM.userDict[obj.card.cardnum]=obj
#写
     with open("xxx.txt","w",encoding="utf-8") as f1:
          for i in ATM.userDict:
          str1 = json.dumps(ATM.userDict.get(i), default=aa1dict)
          f1.write(str1 + "\n")

本系统主要是这养一个界面:


*  1.登陆   2.开户    *
           *  3.查询   4.取款    *
           *  5.存款   0.退出    *
           *  6.转账   7.改密    *
           *  8.锁卡   9.解锁    *
           **********************

下面是完整代码:
Atm类

import time
    import pickle
    import json
    
    class ATM:
        
            userDict={}
            islogin = None
    
        @staticmethod
        def welcome():
            print('''
               **********************
               *                    *
               *  welcome to bank   *
               *                    *
               **********************
               ''')
    
        @staticmethod
        def select():
            print('''
               **********************
               *  1.登陆   2.开户    *
               *  3.查询   4.取款    *
               *  5.存款   0.退出    *
               *  6.转账   7.改密    *
               *  8.锁卡   9.解锁    *
               **********************
               ''')
            num = input("请选择服务项目:")
            return num
    
        # @staticmethod #随机卡号
        def getcardnum(self):
            cardnum = ""
            for x in range(6):
                cardnum += str(random.randrange(0, 10))
            while 1:
                shfblw = 0
                for i in self.userDict:
                    if i == cardnum:
                        shfblw = 1
                        cardnum = ""
                        for x in range(6):
                            cardnum += str(random.randrange(0, 10))
                        break
                if shfblw == 0:
                    break
            return cardnum
    
        # 开户
        # @classmethod
        def openUser(self):
            name = input("请输入您的姓名:")
            idcard = input("请输入您的身份证号码:")
            phonenum = input("请输入您的电话号码:")
            psd = input("请设置您的密码:")
            psd2 = input("请确认您的密码:")
            if psd == psd2:
                mon = int(input("请输入您的预存余额:"))
                if mon>0:
                    cardnum = self.getcardnum()
                    card = Card(cardnum,psd,mon)
                    user = User(name,idcard,phonenum,card)
                    self.userDict[cardnum] = user
                    print("开卡成功,您的卡号为%s,请牢记..."%cardnum)
    
                else:
                    print("预存余额非法,开卡失败...")
    
            else:
                print("两次输入密码不一致,开卡失败...")
    
        # 登入
        @classmethod
        def login(cls):
            cardnum = input("请输入您的卡号:")
            user = cls.userDict.get(cardnum)
            if user:
                print(not(cls.userDict.get(cardnum).card.islock))
                if not(cls.userDict.get(cardnum).card.islock):
                    psd = input("请输入您的密码:")
                    csss = 0
                    while 1:
                        if psd == user.card.password:
                            print("恭喜你,登录成功!!!")
                            cls.islogin = cardnum
                            break
                        else:
                            csss += 1
                            if csss == 3:
                                print("密码输入错误次数过多,该卡已锁")
                                cls.userDict.get(cardnum).card.islock =True
                                break
                            psd = input("密码错误,请输入您的密码:")
                else:
                    print("改卡已锁,请解锁后登入")
            else:
                print("卡号不存在,请查证后登录。。。")
    
        #查询
        @classmethod
        def search(cls):
            print(cls.islogin)
            if cls.islogin:
                print("您当前的余额为%d" % (cls.userDict.get(cls.islogin).card.money))
            else:
                print("请登录后查询")
        #取款
        def withdrawal(self):
            if self.islogin:
                yuee = self.userDict.get(self.islogin).card.money
                print("您当前的余额为%d" %yuee)
                qukan = int(input("请输入取款金额:"))
                if 0 <= qukan <= yuee:
                    print("已成功取款")
                    self.userDict.get(self.islogin).card.money -= qukan
                else:
                    print("输入有误,取款失败")
            else:
                print("请登录后取款")
    
        # 存款
        def deposit(self):
            if self.islogin:
                yuee = self.userDict.get(self.islogin).card.money
                print("您当前的余额为%d" % yuee)
                cunkan = int(input("请输入存款金额:"))
                if 0 <= cunkan:
                    print("已成功存款")
                    self.userDict.get(self.islogin).card.money += cunkan
                else:
                    print("输入有误,存款失败")
            else:
                print("请登录后存款")
    
        #转账
        def transfer(self):
            if self.islogin:
                yue = self.userDict.get(self.islogin).card.money
                print("您当前的余额为%d" %yue)
                zzid = input("请输入转入的账号:")
                if zzid != self.islogin:
                    for i in self.userDict:
                        if i == zzid:
                            zzje = int(input("请输入转账金额:"))
                            if zzje >=0 and zzje <= yue:
                                print("转账成功")
                                self.userDict.get(self.islogin).card.money -= zzje
                                self.userDict.get(zzid).card.money += zzje
                            else:
                                print("输入有误,转账失败")
                            break
                    else:
                        print("请查证后再进行转账")
                else:
                    print("不能转账给自己,转账失败")
            else:
                print("请登录后转账")
    
        #改密
        def close(self):
            if self.islogin:
                # print("您当前的余额为%d" % (self.userDict.get(self.islogin).card.money))
                ylmm = input("请输入原密码")
                if ylmm == self.userDict.get(self.islogin).card.password:
                    xzmm = input("请输入现密码:")
                    xzmm1 = input("请再次输入现密码:")
                    if xzmm == xzmm1:
                        print("改密成功")
                        self.userDict.get(self.islogin).card.password = xzmm
                    else:
                        print("两次密码不一致,改密失败")
                else:
                    print("密码错误,改密失败")
    
            else:
                print("请登录后改密")
        #锁卡
        def lock(self):
            print(self.islogin)
            if self.islogin:
                if self.userDict.get(self.islogin).card.islock == False:
                    print("是否确认锁卡---1.是----2.否")
                    sfqr = input("请输入是否的代表数字:")
                    if sfqr == "1":
                        print("锁卡成功")
                        self.userDict.get(self.islogin).card.islock = True
                        print("退出登入...")
                        self.islogin = None
                    else:
                        print("锁卡失败")
                else:
                    print("该卡已锁")
            else:
                print("请登录后锁卡")
    
            print(self.islogin)
    
        #解锁
        def unlock(self):
            jkid = input("请输入解锁的卡号")
            for i in self.userDict:
                if i == jkid:
                    if self.userDict.get(jkid).card.islock:
                        jsmm = input("请输入该卡密码")
                        if jsmm == self.userDict.get(jkid).card.password:
                            print("解锁成功")
                            self.userDict.get(jkid).card.islock = False
                        else:
                            print("密码错误,解锁失败")
                    else:
                        print("该卡未被锁")
                    break
            else:
                print("输入有误,解锁失败")

Card类

class Card:
        def __init__(self,cardnum,password,money,islock=False):
            self.cardnum = cardnum
            self.password = password
            self.money = money
            self.islock =islock

User类

class  User():
    
        def __init__(self,name,idcard,phonenum,card):
            self.name = name
            self.idcard = idcard
            self.phonenum = phonenum
            self.card = card

运行:

def aa1dict(a):
        a_a = {"name":a.name,"idcard":a.idcard,"phonenum":a.phonenum,"cardnum":a.card.cardnum,"psd":a.card.password,"mon":a.card.money,"islock":a.card.islock}
        return a_a
    #
    def dictaa(d):
        a_aa = Card(d["cardnum"],d["psd"],d["mon"],d["islock"])
        a_b = User(d["name"],d["idcard"],d["phonenum"],a_aa)
        return a_b
    
    if __name__ == '__main__':
        ATM.welcome()
        aa = ATM()
        #pickle模块读取文件读出来的数据就是写进去的数据不需要转换
        # try:
        #     with open("user.txt","rb") as f:
        #         ATM.userDict = pickle.load(f)
        # except:
        #     pass
        
        #json模块读取数据 需要dictaa()方法来转换
        try:
            with open("xxx.txt", "r", encoding="utf-8") as f:
                for line in f.readlines():
                    obj = json.loads(line, object_hook=dictaa)
                    ATM.userDict[obj.card.cardnum]=obj
        except:
            pass
        while True:
            time.sleep(1)
            print(ATM.userDict)
            num = ATM.select()
            if num == "2":
                print("开户")
                aa.openUser()
            elif num == "0":
                print("退出")
                #pickle模块来写文件 主要pickle写的文件和读的文件都是二进制
                # with open("user.txt","wb") as f1:
                #     pickle.dump(ATM.userDict,f1)
                # break
                
                #json模块写文件  把对象以字典的方式写入               
                with open("xxx.txt","w",encoding="utf-8") as f1:
                    for i in ATM.userDict:
                        str1 = json.dumps(ATM.userDict.get(i), default=aa1dict)
                        f1.write(str1 + "\n")
                break
            elif num == "1":
                print("登录")
                ATM.login()
            elif num == "3":
                print("查询")
                ATM.search()
            elif num == "4":
                print("取款")
                aa.withdrawal()
            elif num == "5":
                print("存款")
                aa.deposit()
            elif num == "6":
                print("转账")
                aa.transfer()
            elif num == "7":
                print("改密")
                aa.close()
            elif num == "8":
                print("锁卡")
                aa.lock()
            elif num == "9":
                print("解锁")
                aa.unlock()
            else:
                print("选择有误请重新选择...")