Home >Backend Development >Python Tutorial >Python's practical small project - implementation of banking system

Python's practical small project - implementation of banking system

青灯夜游
青灯夜游forward
2018-10-26 18:02:237966browse

The content of this article is to introduce the implementation of the banking system of Python's practical small project. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

As we all know, no matter how enriched the theoretical knowledge is in the programming process, it still needs to pass the alchemy stone of the project. Let me show you the practical requirements of a small project my apprentice worked on, which was to build a banking system. When we go to the bank to do business, there will be a self-service ATM machine. Now most of the business is solved by him. First think about it for yourself, how to implement this system using object-oriented thinking? What objects are there? What are their respective functions? The more you think about, the better. When implementing it, you encounter a problem and solve it. There are many problems in the process, and it is not easy to solve. But it is through this process that you can learn new things.

1. Preparation

First, walk into the door of the bank. A staff member will ask you what business needs to be processed. Of course, you have to tell the truth, but this has nothing to do with the system (* ̄︶  ̄). Next, if the business to be handled is relatively popular and can be completed on a machine, then she will take us to a huge small machine. He still needs a few operations to make the machine work for us. Sometimes we can ask a more senior employee to input fingerprints. We can understand these as administrators starting the system (some people think it is so troublesome, mainly what I am talking about here are the ones in the bank that have relatively complete functions, not just simple ATMs).

Next it’s time to handle our business. What kind of business are there? Let’s list some first: check the balance, deposit, withdraw, transfer, change the password, you can also report the loss and lock the card, and it can be unlocked accordingly. I have forgotten the most basic ones. How can these operations be done without applying for a card? Opening an account must also be included. Card replacement, account cancellation, etc.

At this point, we don’t have a physical card compared to the actual situation, so there will be some differences. I'll talk about the rest of the process as I think of it.

2. Conversion Thoughts

We have roughly determined the functions that need to be implemented. In the end, we still have to write them into code, so we have to consider those requirements from a programming perspective.

First of all, we must consider what objects are in this system, from people to bank ATMs. People, bank cards, and ATM machines, these three are must-haves. What else is needed? When we start handling business, the person who helps us perform many operations is different from our users. We treat him as an object.

people. What properties does the object human have? People have some of their own information and bank cards, and we artificially determine the remaining business to be handled.

Card. The card also has some information about itself.

ATM. ATM machines have more functions. First of all, they have to implement the functions of deposits and withdrawals listed above. In addition, there is also a staff member's operation on him, which he also has to deal with.

staff member. They have the power to turn the system on and off.

Now that we have the general direction, the rest is just perfecting it bit by bit.

3. Function Implementation

Let’s start with the simple ones. As mentioned earlier, the attributes of customers and cards are relatively simple, so let’s solve them first.

# 银行卡:卡号,卡的密码,余额
class Card(object):
def __init__(self, cardId, cardPasswd, cardMoney):
  self.cardId = cardId
  self.cardPasswd = cardPasswd
  self.cardMony = cardMoney
 # 客户:姓名,身份证号,手机号,银行卡(性别年龄那些只是多了个属性,操作时一样的,就不多写了)
 class User(object):
     def __init__(self, name, idCard, phone, card):
         self.name = name
         self.idCard = idCard
         self.phone = phone
         self.card = card

The above two classes are an initialization for bank card customers. They list the necessary attributes. For example, an ID card must be used to replace a card. Here, it is replaced by an ID number, etc. Among them, the card in the person's attribute is the card defined above, and the person's card attribute includes several internal attributes of the card.

Next, write the functions of the administrator:

  import time
  
  class Admin(object):
      # 为管理员设置个账号密码,为了不随便让人能操作一些危险的内容。
      admin = "1"
      passwd = "1"
      
      # 我们把初始的界面就放在管理员的类里了,他是第一个操作这个机器的嘛
      def printAdminView(self):
         print("****************************************************")
         print("*                                                  *")
         print("*                                                  *")
         print("*               欢迎登陆银行                       *")
         print("*                                                  *")
         print("*                                                  *")
         print("****************************************************")
 
     def printSysFunctionView(self):
         print("****************************************************")
         print("*         开户(1)            查询(2)            *")
        print("*         取款(3)            存款(4)            *")
         print("*         转账(5)            改密(6)            *")
        print("*         锁定(7)            解锁(8)            *")
        print("*         补卡(9)            销户(0)            *")
         print("*                    退出(q)                     *")
         print("****************************************************")
 
     # 这里就是开始时候得验证一下是不是管理员,然后再决定是不是给他这些权利
     def adminOption(self):
         inputAdmin = input("请输入管理员账号:") 
         if self.admin != inputAdmin:
             print("输入账号有误!")
             return -1
         inputPasswd = input("请输入管理员密码:")
         if self.passwd != inputPasswd:
             print("密码输入有误!")
             return -1
 
         # 能执行到这里说明账号密码正确
         print("操作成功,请稍后······")
         time.sleep(2)
         return 0

There is time.sleep() in the above code. This is to make the system more lively and set the delay to simulate the system. Latency when operating on large amounts of data.

The first few are relatively easy to understand, now we start to implement the functions of our system. These are placed in the module of the ATM machine, and strategies can be modified and added if necessary.

Following the order of the directories above, the first function to be implemented is to open an account. To open an account, you have to create a series of attributes. And we need to store this information, otherwise we will find that the card we applied for is no longer valid the next time we come. This information can be stored using a key-value pair, so which attribute should be used for the key. Think about it, name: there may be duplicate names, ID number: this person may apply for more than one card, the safest thing is the card number, there won’t be two cards with the same number. Then the card number is used as the key, and other personal information and bank card information are stored in the value. Now initialize a dictionary under ATM (there are still some problems here, I will talk about it later).

    def __init__(self, allUsers):
        self.allUsers = allUsers # 用户字典
  # 开户
 def creatUser(self):
     # 目标:向用户字典中添加一对键值对(卡号->用户)
     name = input("请输入您的名字:")
     idCard = input("请输入您的身份证号:")
     phone = input("请输入您的电话号码:")
     prestoreMoney = int(input("请输入预存款金额:"))
     if prestoreMoney < 0:
         print("预存款输入有误!开户失败")
         return -1
 
     onePasswd = input("请设置密码:")

     # 生成银行卡号
     cardStr = self.randomCardId() #生成号码通过一个函数来实现,让这里的逻辑更清晰一点
     card = Card(cardStr, onePasswd, prestoreMoney) # 把卡的信息放到这张卡的对象中
 
     user = User(name, idCard, phone, card) # 个人信息也存入客户的对象中
     # 存到字典
     self.allUsers[cardStr] = user # 这就实现了通过一个银行卡号来索引个人信息以及里面的银行卡属性
     print("开户成功!请记住卡号:" + cardStr)

There is no mention of generating bank cards above. This is actually not difficult. Just randomly generate a set of numbers. However, this randomly generated number must not be repeated with the previous card number, otherwise the index There is a problem.

 # 生成卡号
 def randomCardId(self):
     while True:
         str = ""
         for i in range(6):
             ch = chr(random.randrange(ord("0"), ord("9") + 1))
             str += ch
         # 判断是否重复
         if not self.allUsers.get(str): # 这里是通过找一下原来的字典中是否有这个key,如果没有的话那么这个卡号就合法,前面要有个not,没有找到这个卡号那么我们创建这个卡号
             return str

You can already open an account and store it above, but when we actually open an account, we need to enter the password twice to ensure that the password is not accidentally entered incorrectly. In fact, some functions later also require password verification. You can write another function to verify the password, and you can also call it directly when using it in the future.

 # 验证密码
 def checkPasswd(self, realPasswd): # 这里传入的参数就是我们第一次输入的密码,下面要检验第一次输入是不是有误
     for i in range(3):
         tempPasswd = input("请输入密码:")
         if tempPasswd == realPasswd:
             return True
     return False

其实后面的一些功能和这个是类似的,这里就不赘述了,先动手试一试,尽量的想的全面些。我会把完整的代码放在最后,可以参考一下。

最终要实现这些功能还是再写一个主程序比较好,更直观,也方便把理清他们之间的关系。首先主程序里需要调用管理员的登录,之后是客户的使用。管理员的登录上面写了,再调用一下就可以。客户的需求需要把每项功能和操作对应起来。先显示出都有哪些功能可以选择,再操作。比如像这样:

  while True:
      admin.printSysFunctionView()
      # 等待用户操作
      option = input("请输入您的操作:")
      if option == "1":
          # print(&#39;开户&#39;)
          atm.creatUser()
      elif option == "2":
          # print("查询")
         atm.searchUserInfo()
     elif option == "3":
         # print("取款")
         atm.getMoney()
     elif option == "4":
         # print("存储")
         atm.saveMoney()
     elif option == "5":
         # print("转账")
         atm.transferMoney()
     elif option == "6":
         # print("改密")
         atm.changePasswd()
     elif option == "7":
         # print("锁定")
         atm.lockUser()
     elif option == "8":
         # print("解锁")
         atm.unlockUser()
     elif option == "9":
         # print("补卡")
         atm.newCard()
     elif option == "0":
         # print("销户")
         atm.killUser()
     elif option == "q":
         # print("退出")

上面这所有的操作,都需要最终长期存储到键值对中,我们这里先用文件来储存,也可以存储到数据库中。既然要长期存储起来,就得把他序列化到磁盘上,使用pickle库。

 # 每次使用前,需要把内容先加载下来
 filepath = os.path.join(os.getcwd(), "allusers.txt")
 f = open(filepath, "rb")
 allUsers = pickle.load(f)
 atm = ATM(allUsers)
 
 # 而在操作结束的时候,要把操作过的内容重新写到磁盘中
 f = open(filepath, "wb")
 pickle.dump(atm.allUsers, f)
 f.close()

到这里就出现了个问题,pickle.load(),当我们第一次使用时里面并没有存储东西,他自然也就不知道我们想要存储什么样格式的内容。所以第一次我们得手动的创建一个空字典,然后将一组信息存进去。下回使用的时候就可以直接load来使用。

在一开始测试的时候记不得里面存储的内容,我就先写了个查看信息的隐藏功能。后来感觉也许银行后台应该也有这样的功能,就没有删掉,虽然是很简单的显示,至少可以体现出他的思想。有兴趣的同学可以做的更好点。

 # 这是上面使用这个功能的入口,并没有显式的展示出来,仅当管理员这样操作时会调用函数
 elif option == "1122332244":
     admin.ban(allUsers)
 
 # 这里是调用函数后显示所有存储的信息的内容
 def ban(self, allUsers):
     for key in allUsers:
         print("账号:" + key + "\n" + "姓名:" + allUsers[key].name + "\n" + "身份证号:" + allUsers[key].idCard + "\n" + "电话号码:" + allUsers[
                 key].phone + "\n" + "银行卡密码:" + allUsers[key].card.cardPasswd + "\n")

上面我只是把系统的其中一部分拿出来解释了一下,需要把里面的功能完善一下。比如把密码验证等等得放到功能里面,还有一些面向对象的操作,需要创建对象,还需要考虑到每个对象之间的关系,比如银行卡的对象作为客户对象的属性,需要通过参数传进去。仔细琢磨一下,把这个系统完成。在下面放上完整的程序,上面东西不是很清晰的话,那就一点一点的看下面的代码,找找感觉。

import time
import random
import pickle
import os


class Card(object):
    def __init__(self, cardId, cardPasswd, cardMoney):
        self.cardId = cardId
        self.cardPasswd = cardPasswd
        self.cardMony = cardMoney
        self.cardLock = False  # 后面到了锁卡的时候需要有个卡的状态


class User(object):
    def __init__(self, name, idCard, phone, card):
        self.name = name
        self.idCard = idCard
        self.phone = phone
        self.card = card


class Admin(object):
    admin = "1"
    passwd = "1"

    def printAdminView(self):
        print("****************************************************")
        print("*                                                  *")
        print("*                                                  *")
        print("*               欢迎登陆银行                       *")
        print("*                                                  *")
        print("*                                                  *")
        print("****************************************************")

    def printSysFunctionView(self):
        print("****************************************************")
        print("*         开户(1)            查询(2)            *")
        print("*         取款(3)            存款(4)            *")
        print("*         转账(5)            改密(6)            *")
        print("*         锁定(7)            解锁(8)            *")
        print("*         补卡(9)            销户(0)            *")
        print("*                    退出(q)                     *")
        print("****************************************************")

    def adminOption(self):
        inputAdmin = input("请输入管理员账号:")
        if self.admin != inputAdmin:
            print("输入账号有误!")
            return -1
        inputPasswd = input("请输入管理员密码:")
        if self.passwd != inputPasswd:
            print("密码输入有误!")
            return -1

        # 能执行到这里说明账号密码正确
        print("操作成功,请稍后······")
        time.sleep(2)
        return 0

    def ban(self, allUsers):
        for key in allUsers:
            print("账号:" + key + "\n" + "姓名:" + allUsers[key].name + "\n" + "身份证号:" + allUsers[key].idCard + "\n" + "电话号码:" + allUsers[
                key].phone + "\n" + "银行卡密码:" + allUsers[key].card.cardPasswd + "\n")


class ATM(object):
    def __init__(self, allUsers):
        self.allUsers = allUsers # 用户字典

    # 开户
    def creatUser(self):
        # 目标:向用户字典中添加一对键值对(卡号->用户)
        name = input("请输入您的名字:")
        idCard = input("请输入您的身份证号:")
        phone = input("请输入您的电话号码:")
        prestoreMoney = int(input("请输入预存款金额:"))
        if prestoreMoney < 0:
            print("预存款输入有误!开户失败")
            return -1

        onePasswd = input("请设置密码:")
        # 验证密码
        if not self.checkPasswd(onePasswd):
            print("输入密码错误,开户失败!")
            return -1

        # 生成银行卡号
        cardStr = self.randomCardId()
        card = Card(cardStr, onePasswd, prestoreMoney)

        user = User(name, idCard, phone, card)
        # 存到字典
        self.allUsers[cardStr] = user
        print("开户成功!请记住卡号:" + cardStr)

    # 查询
    def searchUserInfo(self):
        cardNum = input("请输入您的卡号:")
        # 验证是否存在该卡号
        user = self.allUsers.get(cardNum)
        if not user:
            print("该卡号不存在,查询失败!")
            return -1
        # 判断是否锁定
        if user.card.cardLock:
            print("该卡已锁定!请解锁后再使用其功能!")
            return -1

        # 验证密码
        if not self.checkPasswd(user.card.cardPasswd):
            print("密码输入有误,该卡已锁定!请解锁后再使用其功能!")
            user.card.cardLock = True
            return -1
        print("账号:%s   余额:%d" % (user.card.cardId, user.card.cardMony))

    # 取款
    def getMoney(self):
        cardNum = input("请输入您的卡号:")
        # 验证是否存在该卡号
        user = self.allUsers.get(cardNum)
        if not user:
            print("该卡号不存在,取款失败!")
            return -1
        # 判断是否锁定
        if user.card.cardLock:
            print("该卡已锁定!请解锁后再使用其功能!")
            return -1

        # 验证密码
        if not self.checkPasswd(user.card.cardPasswd):
            print("密码输入有误,该卡已锁定!请解锁后再使用其功能!")
            user.card.cardLock = True
            return -1

        # 开始取款
        amount = int(input("验证成功!请输入取款金额:"))
        if amount > user.card.cardMony:
            print("取款金额有误,取款失败!")
            return -1
        if amount < 0:
            print("取款金额有误,取款失败!")
            return -1
        user.card.cardMony -= amount
        print("您取款%d元,余额为%d元!" % (amount, user.card.cardMony))

    # 存款
    def saveMoney(self):
        cardNum = input("请输入您的卡号:")
        # 验证是否存在该卡号
        user = self.allUsers.get(cardNum)
        if not user:
            print("该卡号不存在,存款失败!")
            return -1
        # 判断是否锁定
        if user.card.cardLock:
            print("该卡已锁定!请解锁后再使用其功能!")
            return -1

        # 验证密码
        if not self.checkPasswd(user.card.cardPasswd):
            print("密码输入有误,该卡已锁定!请解锁后再使用其功能!")
            user.card.cardLock = True
            return -1

        # 开始存款
        amount = int(input("验证成功!请输入存款金额:"))
        if amount < 0:
            print("存款金额有误,存款失败!")
            return -1
        user.card.cardMony += amount
        print("您存款%d元,最新余额为%d元!" % (amount, user.card.cardMony))

    # 转账
    def transferMoney(self):
        cardNum = input("请输入您的卡号:")
        # 验证是否存在该卡号
        user = self.allUsers.get(cardNum)
        if not user:
            print("该卡号不存在,转账失败!")
            return -1
        # 判断是否锁定
        if user.card.cardLock:
            print("该卡已锁定!请解锁后再使用其功能!")
            return -1

        # 验证密码
        if not self.checkPasswd(user.card.cardPasswd):
            print("密码输入有误,该卡已锁定!请解锁后再使用其功能!")
            user.card.cardLock = True
            return -1

        # 开始转账
        amount = int(input("验证成功!请输入转账金额:"))
        if amount > user.card.cardMony or amount < 0:
            print("金额有误,转账失败!")
            return -1

        newcard = input("请输入转入账户:")
        newuser = self.allUsers.get(newcard)
        if not newuser:
            print("该卡号不存在,转账失败!")
            return -1
        # 判断是否锁定
        if newuser.card.cardLock:
            print("该卡已锁定!请解锁后再使用其功能!")
            return -1
        user.card.cardMony -= amount
        newuser.card.cardMony += amount
        time.sleep(1)
        print("转账成功,请稍后···")
        time.sleep(1)
        print("转账金额%d元,余额为%d元!" % (amount, user.card.cardMony))

    # 改密
    def changePasswd(self):
        cardNum = input("请输入您的卡号:")
        # 验证是否存在该卡号
        user = self.allUsers.get(cardNum)
        if not user:
            print("该卡号不存在,改密失败!")
            return -1
        # 判断是否锁定
        if user.card.cardLock:
            print("该卡已锁定!请解锁后再使用其功能!")
            return -1

        # 验证密码
        if not self.checkPasswd(user.card.cardPasswd):
            print("密码输入有误,该卡已锁定!请解锁后再使用其功能!")
            user.card.cardLock = True
            return -1
        print("正在验证,请稍等···")
        time.sleep(1)
        print("验证成功!")
        time.sleep(1)

        # 开始改密
        newPasswd = input("请输入新密码:")
        if not self.checkPasswd(newPasswd):
            print("密码错误,改密失败!")
            return -1
        user.card.cardPasswd = newPasswd
        print("改密成功!请稍后!")

    # 锁定
    def lockUser(self):
        cardNum = input("请输入您的卡号:")
        # 验证是否存在该卡号
        user = self.allUsers.get(cardNum)
        if not user:
            print("该卡号不存在,锁定失败!")
            return -1
        if user.card.cardLock:
            print("该卡已被锁定,请解锁后再使用其功能!")
            return -1
        if not self.checkPasswd(user.card.cardPasswd):
            print("密码输入有误,锁定失败!")
            return -1
        tempIdCard = input("请输入您的身份证号码:")
        if tempIdCard != user.idCard:
            print("身份证号输入有误,锁定失败!")
            return -1
        # 锁定
        user.card.cardLock = True
        print("锁定成功!")


    # 解锁
    def unlockUser(self):
        cardNum = input("请输入您的卡号:")
        # 验证是否存在该卡号
        user = self.allUsers.get(cardNum)
        if not user:
            print("该卡号不存在,解锁失败!")
            return -1
        if not user.card.cardLock:
            print("该卡未被锁定,无需解锁!")
            return -1
        if not self.checkPasswd(user.card.cardPasswd):
            print("密码输入有误,解锁失败!")
            return -1
        tempIdCard = input("请输入您的身份证号码:")
        if tempIdCard != user.idCard:
            print("身份证号输入有误,解锁失败!")
            return -1
        # 解锁
        user.card.cardLock = False
        print("解锁成功!")

    # 补卡
    def newCard(self):
        cardNum = input("请输入您的卡号:")
        # 验证是否存在该卡号
        user = self.allUsers.get(cardNum)
        if not user:
            print("该卡号不存在!")
            return -1
        tempname = input("请输入您的姓名:")
        tempidcard = input("请输入您的身份证号码:")
        tempphone = input("请输入您的手机号码:")
        if tempname != self.allUsers[cardNum].name\
                or tempidcard != self.allUsers.idCard\
                or tempphone != self.allUsers.phone:
            print("信息有误,补卡失败!")
            return -1
        newPasswd = input("请输入您的新密码:")
        if not self.checkPasswd(newPasswd):
            print("密码错误,补卡失败!")
            return -1
        self.allUsers.card.cardPasswd = newPasswd
        time.sleep(1)
        print("补卡成功,请牢记您的新密码!")

    # 销户
    def killUser(self):
        cardNum = input("请输入您的卡号:")
        # 验证是否存在该卡号
        user = self.allUsers.get(cardNum)
        if not user:
            print("该卡号不存在,转账失败!")
            return -1
        # 判断是否锁定
        if user.card.cardLock:
            print("该卡已锁定!请解锁后再使用其功能!")
            return -1

        # 验证密码
        if not self.checkPasswd(user.card.cardPasswd):
            print("密码输入有误,该卡已锁定!请解锁后再使用其功能!")
            user.card.cardLock = True
            return -1

        del self.allUsers[cardNum]
        time.sleep(1)
        print("销户成功,请稍后!")

    # 验证密码
    def checkPasswd(self, realPasswd):
        for i in range(3):
            tempPasswd = input("请输入密码:")
            if tempPasswd == realPasswd:
                return True
        return False

    # 生成卡号
    def randomCardId(self):
        while True:
            str = ""
            for i in range(6):
                ch = chr(random.randrange(ord("0"), ord("9") + 1))
                str += ch
            # 判断是否重复
            if not self.allUsers.get(str):
                return str


# 主函数,不在上面的类中
def main():
    # 界面对象
    admin = Admin()

    # 管理员开机
    admin.printAdminView()
    if admin.adminOption():
        return -1

    # 由于一开始文件里并没有数据,不知道要存的是个字典,先存一个,后面再把这个关了
    # allUsers = {}

    # 提款机对象
    filepath = os.path.join(os.getcwd(), "allusers.txt")
    f = open(filepath, "rb")
    allUsers = pickle.load(f)
    atm = ATM(allUsers)

    while True:
        admin.printSysFunctionView()
        # 等待用户操作
        option = input("请输入您的操作:")
        if option == "1":
            # print(&#39;开户&#39;)
            atm.creatUser()
        elif option == "2":
            # print("查询")
            atm.searchUserInfo()
        elif option == "3":
            # print("取款")
            atm.getMoney()
        elif option == "4":
            # print("存储")
            atm.saveMoney()
        elif option == "5":
            # print("转账")
            atm.transferMoney()
        elif option == "6":
            # print("改密")
            atm.changePasswd()
        elif option == "7":
            # print("锁定")
            atm.lockUser()
        elif option == "8":
            # print("解锁")
            atm.unlockUser()
        elif option == "9":
            # print("补卡")
            atm.newCard()
        elif option == "0":
            # print("销户")
            atm.killUser()
        elif option == "q":
            # print("退出")
            if not admin.adminOption():
                # 将当前系统中的用户信息保存到文件当中
                f = open(filepath, "wb")
                pickle.dump(atm.allUsers, f)
                f.close()
                return -1
        elif option == "1122332244":
            admin.ban(allUsers)

        time.sleep(2)

if __name__ == "__main__":
    main()

上面就是整个系统了,其实主要还是思想,模块较多,没有全部解释,如果程序当中有哪里不理解,可以留言讨论。注意上述完整代码主要是供大家了解整个系统,想要实现还需在自己电脑上重新配置,注意那些文件的路径,还有一个存放信息的txt文件,把他搞懂后,相信让他运行起来不难。

The above is the detailed content of Python's practical small project - implementation of banking system. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete