python小练习之三---购物车程序

购物车购物的例子

严格来讲,这个例子相对大一些
功能也稍完备一些,具有用户登录,商品上架,用户购物,放入购物车,展示每个用户的购物车里的商品的数量,用户账户余额,支持用户账户充值等
下面展示的代码有些不完善,需要继续修改
程序写了快300行了,是不是可以优化一下

'''
购物车
1. 商品信息- 数量、单价、名称
2. 用户信息- 帐号、密码、余额
3. 用户可充值
4. 购物历史信息
5. 允许用户多次购买,每次可购买多件
6. 余额不足时进行提醒
7. 用户退出时,输出档次购物信息
8. 用户下次登陆时可查看购物历史
9. 商品列表分级
'''

import json

class Article(object):

    def __init__(self, **kwargs):
        self.attr = kwargs
        # article_list.append(kwargs)


class User(object):

    def __init__(self):
        self.userchoice = 0
        self.userlist = list()
        self.username = str()
        self.password = str()
        self.balance = int()
        # 用户名是否被使用了
        self.nameused = 0
        # 用户的用户名+密码是否能匹配
        self.user_correct = 0
        # 用户是否存在
        self.user_exist = 0
        # 用户登录尝试次数
        self.login_try_count = 0
        # 用户登录允许最大尝试次数为3次
        self.login_limit_count = 3
        # 用户是否已经登录
        self.login_status = 0

    def GenUserList(self):
        self.userlist = list()
        with open("userlist", "a+") as fd_userlist:
            for line in fd_userlist:
                if line.rstrip("
"):
                    self.userlist.append(line.rstrip("
"))

    def WriteUserList(self, username):
        username = self.username
        with open("userlist", "a+") as fd_userlist:
            fd_userlist.write(self.username)
            fd_userlist.write("
")

    def UsernameCheck(self, username):
        self.GenUserList()
        self.nameused = 0
        username = self.username
        if self.username in self.userlist:
            print '%s 用户名已经使用过了,请重新选择用户名' %(self.username)
            self.nameused = 1
        elif self.UserExist(self.username) == 1:
            self.nameused = 0
        return self.nameused

    def UserExist(self, username):
        with open("userprofile", "a+") as fd:
            for line in fd:
                if line.find(username) == 0:
                    self.user_exist = 1
                    return self.user_exist
                else:
                    self.user_exist = 0
                    return self.user_exist

    def UserRegister(self):
        input_username = raw_input("请输入用户名:")
        self.username = input_username.strip()
        if self.UsernameCheck(self.username) == 0:
            input_password = raw_input('请输入密码:').strip()
            int_balance = 100
            self.password = input_password
            self.balance = self.UserCalBalance(int_balance)
            print "self.balance" , self.balance
            with open('userprofile', 'a+') as fd_userprofile:
                 # fd_userprofile.write('username:' + self.username + '|')
                 # fd_userprofile.write('password:' + self.password)
                 fd_userprofile.write(self.username + '|')
                 fd_userprofile.write(self.password + '|')
                 fd_userprofile.write(str(self.balance))
                 fd_userprofile.write("
")
                 self.WriteUserList(self.username)
        else:
            self.UserRegister()

    def UserCorrect(self, username, password):
        userProfile_dict_list = list()
        with open("userprofile", "a+") as fd:
            for line in fd:
                u, temp_p, initbalance = line.split("|")
                p = temp_p.strip()
                userProfile_dict_list.append({'username': u, 'password':
                            p})
        length = len(userProfile_dict_list)
        for i in xrange(length):
            if username == userProfile_dict_list[i]['username']:
                if password == userProfile_dict_list[i]['password']:
                    self.user_correct = 1
                    return self.user_correct
                else:
                    self.user_correct = 0
                    return self.user_correct
            # return self.user_correct

    def UserCalBalance(self, balance):
        self.balance += balance
        return self.balance

    def UserLogin(self):
        userProfile_dict_list = list()
        input_username = raw_input("登录用户名:").strip()
        input_password = raw_input("登录密码:").strip()
        self.user_correct = self.UserCorrect(input_username, input_password)
        self.user_exist = self.UserExist(input_username)
        if self.user_correct == 1:
            print "欢迎登录:", input_username
            self.login_status = 1
        elif self.user_exist == 1:
           print "密码错误"
           self.login_try_count += 1
           print "%s 还有 %d 次尝试机会" %(input_username,
                   self.login_limit_count - self.login_try_count)
           if self.login_try_count < 3:
               self.UserLogin()
           else:
               print "%s 已经尝试3次登录失败" %(input_username)
               self.login_status = 0
               self.UserExit()
        elif self.user_exist == 0:
            print "%s 用户不存在" %(input_username)
            print "请去注册"
            self.UserRegister()

    def UserCharge(self):
        charge = int(raw_input("请输入充值金额:")).strip()
        self.balance += charge

    def UserExit(self):
        print "Bye Bye"
        exit(0)

    def ProcessUserChoice(self):
        if self.userchoice == 1:
            self.UserRegister()
        elif self.userchoice == 2:
            self.UserLogin()
        elif self.userchoice == 3:
            self.UserCharge()
        elif self.userchoice == 4:
            CMain()
        elif self.userchoice == 5:
            self.UserExit()
        else:
            self.userchoice = int(raw_input("请输入正确的选择,
                    1或者2或者3或者4或者5:"))
            self.ProcessUserChoice()

    def InitInterface(self):
        failedCount = 0
        login_status = dict()
        u_profile_dict_list = list()
        while True:
            try:
               self.userchoice = int(raw_input("----------------
"
                                    "用户操作菜单
"
                                    "----------------
"
                                    "1:注册
"
                                    "2:登录
"
                                    "3:充值
"
                                    "4:购物
"
                                    "5:退出
"
                                    "----------------
"
                                    "请选择:").strip())
               self.ProcessUserChoice()
            except Exception as e:
                print e
                self.InitInterface()


class Cart(object):

    def __init__(self, kwargs):
        self.cart_attr = kwargs

def userMain():
    user = User()
    user.InitInterface()

def addArticle():
    while True:
        choice = int(raw_input("----------------
"
               "商品操作菜单
"
               "----------------
"
               "请输入你的选择
"
               "1:添加商品
"
               "2:继续
"
               "3:退出商品操作,进入用户操作
"))
        if choice == 3:
            print('bye bye!')
            userMain()
        elif choice == 1 or choice == 2:
            article_name = raw_input("请输入商品名:")
            article_price = raw_input("请输入商品价格:")
            article_amount = raw_input("请输入商名数量:")
            article = Article(**{'article_name': article_name,
                'article_pricie': article_price, 'article_amount':
                article_amount})
            article_lst.append(article.attr)
            # print article_lst
        with open('article', 'a+') as fd_article:
            for item in article_lst:
                print item
                fd_article.write(json.dumps(item))
                fd_article.write(',')

def addCart():
    user = User()
    if user.UserLogin() == 1:
        while True:
            choice = int(raw_input("----------------
"
                   "商品操作菜单
"
                   "----------------
"
                   "请输入你的选择
"
                   "1:购买商品
"
                   "2:退出购买商品操作,显示用户本次购买记录
"))
            if choice == 3:
                print('bye bye!')
                userMain()
            elif choice == 1 or choice == 2:
                user_article_name = raw_input("请输入商品名:")
                user_article_price = raw_input("请输入商品价格:")
                user_article_amount = raw_input("请输入商名数量:")
                user_article = Article(**{input_username,
                        {'article_name': article_name,
                         'article_pricie': article_price, 
                         'article_amount': article_amount}})
                user_cart_lst.append(article.attr)
                # print article_lst
            with open('article', 'a+') as fd_article:
                for item in user_cart_lst:
                    print item
                    fd_article.write(json.dumps(item))
                    fd_article.write(',')

def UMain():
    addArticle()

def CMain():
    addCart()


if __name__ == '__main__':
    article_lst = list()
    user_cart_lst = list()
    UMain()
    CMain()
	```
原文地址:https://www.cnblogs.com/haozike/p/8689018.html