视频3:20代码冗余

视频3:20代码冗余

视频3:20中

current_gift_pool[second_level] = current_second_gift_pool
gifts[first_level] = current_gift_pool

这段代码是多余的,因为下面这段代码直接修改了gifts的值,直接将gifts写入gift_json即可


gifts = self.__read_gifts()
current_gift_pool = gifts[first_level]
current_second_gift_pool = current_gift_pool[second_level]
if gift_name in current_second_gift_pool:
    current_second_gift_pool[gift_name]['count'] += gift_count
else:
    current_second_gift_pool[gift_name] = {
        'name': gift_name,
        'count': gift_count
    }
    }

相应的

current_gift_pool = gifts[first_level]
current_second_gift_pool = current_gift_pool[second_level]
if gift_name in current_second_gift_pool:

也可改成

current_second_gift_pool = gifts[first_level][second_level]
if gift_name in current_second_gift_pool:


正在回答

登陆购买课程后可参与讨论,去登陆

1回答

同学,你好!经测试同学说的冗余是正确的,可以省略。同学说的修改也是可以的。棒棒哒~

祝学习愉快~

  • Mr朱_ 提问者 #1

    老师可以把这 2 行 注释掉再运行看看
    current_gift_pool[second_level] = current_second_gift_pool
    gifts[first_level] = current_gift_pool

    2023-06-01 19:28:49
  • Mr朱_ 提问者 #2
    # coding:utf-8
    
    """
        1:导入user.json   文件检查
        2:导入gift.json   文件检查
        1:确定用户表中每个用户的信息字段
        2:读取userjson文件
        3:写入userjson文件(检测该用户使用存在)存在则不写入
    
        user存储结构:
        username    姓名
        role        normal or admin
        active      True or False
        create_time timestamp
        update_time timestamp
        gifts       []
    
        '小明': {username: '小明', role: admin, active: True, create_time: time, update_time: time, gifts: []}
        1:role 的修改
        2:active 的修改
        3:delete_user
        1:gifts 奖品结构的确定
        2:gifts 奖品的读取
        3:gifts 添加
        4:gifts 初始化
    
        奖品结构:{
            level1: {
                level1: {
                    gift_name1: {
                        name: xx
                        count: xx
                    }
                    gift_name2: {
                        name: xx
                        count: xx
                    }
                }
                level2: {}
                level3: {}
            }
            level2: {}
            level3: {}
    
        }
        1:gifts 修改(数量递减)
        2:gifts 奖品删除
    
    
    """
    
    import os
    import time
    import json
    from common.utils import check_file, timestamp_to_string
    from common.error import UserExistsError, RoleError, LevelError, NegativeNomberError
    from common.consts import ROLES, FIRSTLEVEL, SECONDLEVEL
    
    
    class Base(object):
        def __init__(self, user_json, gift_json):
            self.user_json = user_json
            self.gift_json = gift_json
    
            self.__check_user_json()
            self.__check_gift_json()
            self.__init_gifts()
    
        def __check_user_json(self):  # 检查传入文件是否合法
            check_file(self.user_json)
    
        def __check_gift_json(self):  # 检查传入文件是否合法
            check_file(self.gift_json)
    
        def __save(self, path, data):
            with open(path, 'w') as f:
                f.write(json.dumps(data))
    
        def __read_users(self, time_to_str=False):  # 返回用户信息
            with open(self.user_json, 'r') as f:
                data = json.loads(f.read())
    
            if time_to_str:
                for k, v in data.items():
                    v['create_time'] = timestamp_to_string(v['create_time'])
                    v['update_time'] = timestamp_to_string(v['update_time'])
            return data
    
        def __write_user(self, **user):  # 写入用户初始化信息
            if 'username' not in user:
                raise ValueError('missing username')
            if 'role' not in user:
                raise ValueError('missing role')
    
            user['active'] = True
            user['create_time'] = time.time()
            user['update_time'] = time.time()
            user['gifts'] = []
    
            users = self.__read_users()
    
            if user['username'] in users:
                raise UserExistsError(f'username {user["username"]} had exists')
    
            users.update({user['username']: user})
            print(users)
            self.__save(self.user_json, users)
            return True
    
        def __change_role(self, username, role):
            users = self.__read_users()
            user = users.get(username)
            if not user:
                return False
    
            if role not in ROLES:
                raise RoleError(f'not use role {role}')
    
            user['role'] = role
            user['update_time'] = time.time()
            users[username] = user
    
            self.__save(self.user_json, users)
            return True
    
        def __change_active(self, username):
            users = self.__read_users()
            user = users.get(username)
            if not user:
                return False
            user['active'] = not user['active']
            user['update_time'] = time.time()
            users[username] = user
    
            self.__save(self.user_json, users)
            return True
    
        def __delete_user(self, username):
            users = self.__read_users()
            user = users.get(username)
            if not user:
                return False
            deleted_user = users.pop(username)
            self.__save(self.user_json, users)
            return deleted_user
    
        def __read_gifts(self):
            with open(self.gift_json, 'r') as f:
                return json.loads(f.read())
    
        def __init_gifts(self):
            data = {
                'level1': {
                    'level1': {},
                    'level2': {},
                    'level3': {}
                },
                'level2': {
                    'level1': {},
                    'level2': {},
                    'level3': {}
                },
                'level3': {
                    'level1': {},
                    'level2': {},
                    'level3': {}
                },
                'level4': {
                    'level1': {},
                    'level2': {},
                    'level3': {}
                }
            }
            gifts = self.__read_gifts()
            if gifts:
                return
    
            self.__save(self.gift_json, data)
    
        def write_gift(self, first_level, second_level, gift_name, gift_count):
            gifts, current_second_gift_pool = self.__check_and_getgift(first_level, second_level)
    
            if gift_count <= 0:
                gift_count = 1
    
            if gift_name in current_second_gift_pool:
                current_second_gift_pool[gift_name]['count'] += gift_count
            else:
                current_second_gift_pool[gift_name] = {
                    'name': gift_name,
                    'count': gift_count
                }
            self.__save(path=self.gift_json, data=gifts)
    
        def __gift_update(self, first_level, second_level, gift_name, gift_count=1):
            gifts, current_second_gift_pool = self.__check_and_getgift(first_level, second_level)
    
            if gift_count <= 0:
                gift_count = 1
    
            if gift_name not in current_second_gift_pool:
                return False
            if current_second_gift_pool[gift_name]['count'] - gift_count < 0:
                raise NegativeNomberError('gift count can not negative')
    
            current_second_gift_pool[gift_name]['count'] -= gift_count
    
            self.__save(self.gift_json, gifts)
    
        def __delete_gift(self, first_level, second_level, gift_name):
            gifts, current_second_gift_pool = self.__check_and_getgift(first_level, second_level)
            if gift_name not in current_second_gift_pool:
                return False
            delete_gift_data = current_second_gift_pool.pop(gift_name)
            self.__save(self.gift_json, gifts)
            return delete_gift_data
    
        def __check_and_getgift(self, first_level, second_level):
            if first_level not in FIRSTLEVEL:
                raise LevelError('first level not exists')
            if second_level not in SECONDLEVEL:
                raise LevelError('second level not exists')
    
            gifts = self.__read_gifts()
            current_second_gift_pool = gifts[first_level][second_level]
            return gifts, current_second_gift_pool
    
    
    
    if __name__ == '__main__':
        gift_path = os.path.join(os.getcwd(), 'storage', 'gift.json')
        user_path = os.path.join(os.getcwd(), 'storage', 'user.json')
        print(f'{gift_path}\n{user_path}')
        base = Base(user_json=user_path, gift_json=gift_path)
        # base.write_user(username='dewei', role='admin')
        # base.__write_user(username='xiaomu', role='admin')
        # result = base.delete_user('dewei')
        # print(result)
        base.write_gift('level1', 'level1', 'iphone11', 10)


    2023-06-01 20:51:39
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师