亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python學習之異常斷言詳解

 更新時間:2022年03月17日 08:37:18   作者:渴望力量的哈士奇  
這篇文章主要和大家介紹一下異常的最后一個知識點——斷言 ,斷言是判斷一個表達式,在表達式為 False 的時候觸發(fā)異常。本文將通過示例詳細介紹一下斷言,需要的可以參考一下

該章節(jié)我們來學習 異常的最后一個知識點 - 斷言 ,斷言是判斷一個表達式,在表達式為 False 的時候觸發(fā)異常。表達式我們可以對號入座,可以是條件語句中的聲明,也可以是是 while 循環(huán)中的聲明。

它們都是對一件事情進行 True 或者 False 的判斷, 斷言 也是如此,斷言發(fā)現(xiàn)后面的表達式為 False 的時候 就會主動拋出異常。

在 Python 中 assert 就是斷言的關鍵字,乍一聽起來 似乎和 raise 關鍵字 的功能一樣。其實 assert 斷言的使用要比 raise 更加的簡潔, rais 是生硬的拋出一個異常,而 assert 是先進行一個判斷然后再根據(jù)結果選擇是否要拋出這個異常。

比如我們對自己寫的函數(shù)的結果進行一個判斷,如果選擇 raise 則需要自己手動寫一個 if 按斷的條件語句,然后再進行 raise ;而 assert 只要一行就可以輕松完成我們的任務

斷言的功能與語法

斷言的功能:簡單來說,斷言就是用于判斷的一個表達式,當表達式的條件返回為 False 的時候觸發(fā)異常。

斷言的語法:示例如下

# 用法:
assert exception, message

# 參數(shù):
# exception:表達式,一般是判斷相等;或者是判斷是某種數(shù)據(jù)類型的 bool 判斷的語句,再決定是否拋出異常
# message:指的是具體的錯誤信息,選填參數(shù),可以不填寫。(但是建議還是填寫上)
# 返回值:無返回值(雖然表達式有返回值,但 assert 沒有;表達式為 Treu , assert 將不會觸發(fā)任何異常)

看一個簡單的例子:

assert 1 != 1, '返回結果 \'False\' 1 等于 1'

# >>> 執(zhí)行結果如下:
# >>> AssertionError: 返回結果 'False' 1 等于 1


# ********************************************


assert 1 > 2, '返回結果 \'False\' ,拋出異常'

# >>> 執(zhí)行結果如下:
# >>> AssertionError: 返回結果 'False' ,拋出異常

斷言小實戰(zhàn)

接下來我們根據(jù)我們之前面向對象章節(jié)的Python學習之面向函數(shù)轉面向對象詳解進行添加異常及異常的捕獲然后再增加一個批量添加的功能。

源碼如下:

"""
    @Author:Neo
    @Date:2020/1/16
    @Filename:students_info.py
    @Software:Pycharm
"""


class NotArgError(Exception):
    def __init__(self, message):
        self.message = message


class StudentInfo(object):
    def __init__(self, students):
        self.students = students

    def get_by_id(self, student_id):
        return self.students.get(student_id)

    def get_all_students(self):
        for id_, value in self.students.items():
            print('學號:{}, 姓名:{}, 年齡:{}, 性別:{}, 班級:{}'.format(
                id_, value['name'], value['age'], value['sex'], value['class_number']
            ))
        return self.students

    def add(self, **student):
        try:
            self.check_user_info(**student)
        except Exception as e:
            raise e
        self.__add(**student)

    def adds(self, new_students):
        for student in new_students:
            try:
                self.check_user_info(**student)
            except Exception as e:
                print(e, student.get('name'))
                continue
            self.__add(**student)

    def __add(self, **student):
        new_id = max(self.students) + 1
        self.students[new_id] = student

    def delete(self, student_id):
        if student_id not in self.students:
            print('{} 并不存在'.format(student_id))
        else:
            user_info = self.students.pop(student_id)
            print('學號是{}, {}同學的信息已經(jīng)被刪除了'.format(student_id, user_info['name']))

    def deletes(self, ids):
        for id_ in ids:
            if id_ not in self.students:
                print(f'{id_} 不存在學生庫中')
                continue
            student_info = self.students.pop(id_)
            print(f'學號{id_} 學生{student_info["name"]} 已被移除')

    def update(self, student_id, **kwargs):
        if student_id not in self.students:
            print('并不存在這個學號:{}'.format(student_id))
        try:
            self.check_user_info(**kwargs)
        except Exception as e:
            raise e

        self.students[student_id] = kwargs
        print('同學信息更新完畢')

    def updates(self, update_students):
        for student in update_students:
            try:
                id_ = list(student.keys())[0]
            except IndexError as e:
                print(e)
                continue
            if id_ not in self.students:
                print(f'學號{id_} 不存在')
                continue
            user_info = student[id_]
            try:
                self.check_user_info(**user_info)
            except Exception as e:
                print(e)
                continue
            self.students[id_] = user_info
        print('所有用戶信息更新完成')

    def search_users(self, **kwargs):

        assert len(kwargs) == 1, '參數(shù)數(shù)量傳遞錯誤'

        values = list(self.students.values())
        key = None
        value = None
        result = []

        if 'name' in kwargs:
            key = 'name'
            value = kwargs[key]
        elif 'sex' in kwargs:
            key = 'sex'
            value = kwargs['sex']
        elif 'class_number' in kwargs:
            key = 'class_number'
            value = kwargs[key]
        elif 'age' in kwargs:
            key = 'age'
            value = kwargs[key]
        else:
            raise NotArgError('沒有發(fā)現(xiàn)搜索的關鍵字')

        for user in values:  # [{name, sex, age, class_number}, {}]
            if value in user[key]:
                result.append(user)
        return result

    def check_user_info(self, **kwargs):
        assert len(kwargs) == 4, '參數(shù)必須是4個'

        if 'name' not in kwargs:
            raise NotArgError('沒有發(fā)現(xiàn)學生姓名參數(shù)')
        if 'age' not in kwargs:
            raise NotArgError('缺少學生年齡參數(shù)')
        if 'sex' not in kwargs:
            raise NotArgError('缺少學生性別參數(shù)')
        if 'class_number' not in kwargs:
            raise NotArgError('缺少學生班級參數(shù)')

        name_value = kwargs['name']  # type(name_value)
        age_value = kwargs['age']
        sex_value = kwargs['sex']
        class_number_value = kwargs['class_number']
        # isinstace(對比的數(shù)據(jù), 目標類型) isinstance(1, str)

        if not isinstance(name_value, str):
            raise TypeError('name應該是字符串類型')
        if not isinstance(age_value, int):
            raise TypeError('age 應該是整型')
        if not isinstance(sex_value, str):
            raise TypeError('sex應該是字符串類型')
        if not isinstance(class_number_value, str):
            raise TypeError('class_number應該是字符串類型')


students = {
    1: {
        'name': 'Neo',
        'age': 18,
        'class_number': 'A',
        'sex': 'boy'
    },
    2: {
        'name': 'Jack',
        'age': 16,
        'class_number': 'B',
        'sex': 'boy'
    },
    3: {
        'name': 'Lily',
        'age': 18,
        'class_number': 'A',
        'sex': 'girl'
    },
    4: {
        'name': 'Adem',
        'age': 18,
        'class_number': 'C',
        'sex': 'boy'
    },
    5: {
        'name': 'HanMeiMei',
        'age': 18,
        'class_number': 'B',
        'sex': 'girl'
    }
}

if __name__ == '__main__':
    student_info = StudentInfo(students)
    user = student_info.get_by_id(1)
    student_info.add(name='Marry', age=16, class_number='A', sex='girl')
    users = [
        {'name': 'Atom', 'age': 17, 'class_number': 'B', 'sex': 'boy'},
        {'name': 'Lucy', 'age': 18, 'class_number': 'C', 'sex': 'girl'}
    ]
    student_info.adds(users)
    student_info.get_all_students()
    print('------------------------------------------------------')

# >>> 執(zhí)行結果如下:
# >>> 學號:1, 姓名:Neo, 年齡:18, 性別:boy, 班級:A
# >>> 學號:2, 姓名:Jack, 年齡:16, 性別:boy, 班級:B
# >>> 學號:3, 姓名:Lily, 年齡:18, 性別:girl, 班級:A
# >>> 學號:4, 姓名:Adem, 年齡:18, 性別:boy, 班級:C
# >>> 學號:5, 姓名:HanMeiMei, 年齡:18, 性別:girl, 班級:B
# >>> 學號:6, 姓名:Marry, 年齡:16, 性別:girl, 班級:A
# >>> 學號:7, 姓名:Atom, 年齡:17, 性別:boy, 班級:B
# >>> 學號:8, 姓名:Lucy, 年齡:18, 性別:girl, 班級:C
# >>> ------------------------------------------------------

    student_info.deletes([7, 8])
    student_info.get_all_students()
    print('------------------------------------------------------')

# >>> 執(zhí)行結果如下:
# >>> ------------------------------------------------------
# >>> 學號7 學生Atom 已被移除
# >>> 學號8 學生Lucy 已被移除
# >>> 學號:1, 姓名:Neo, 年齡:18, 性別:boy, 班級:A
# >>> 學號:2, 姓名:Jack, 年齡:16, 性別:boy, 班級:B
# >>> 學號:3, 姓名:Lily, 年齡:18, 性別:girl, 班級:A
# >>> 學號:4, 姓名:Adem, 年齡:18, 性別:boy, 班級:C
# >>> 學號:5, 姓名:HanMeiMei, 年齡:18, 性別:girl, 班級:B
# >>> 學號:6, 姓名:Marry, 年齡:16, 性別:girl, 班級:A
# >>> ------------------------------------------------------


    student_info.updates([
        {1: {'name': 'Jone', 'age': 18, 'class_number': 'A', 'sex': 'boy'}},
        {2: {'name': 'Nike', 'age': 18, 'class_number': 'A', 'sex': 'boy'}}
    ])
    student_info.get_all_students()
    print('------------------------------------------------------')

# >>> 執(zhí)行結果如下:
# >>> ------------------------------------------------------
# >>> 所有用戶信息更新完成
# >>> 學號:1, 姓名:Jone, 年齡:18, 性別:boy, 班級:A
# >>> 學號:2, 姓名:Nike, 年齡:18, 性別:boy, 班級:A
# >>> 學號:3, 姓名:Lily, 年齡:18, 性別:girl, 班級:A
# >>> 學號:4, 姓名:Adem, 年齡:18, 性別:boy, 班級:C
# >>> 學號:5, 姓名:HanMeiMei, 年齡:18, 性別:girl, 班級:B
# >>> 學號:6, 姓名:Marry, 年齡:16, 性別:girl, 班級:A
# >>> ------------------------------------------------------


    result = student_info.search_users(name='d')
    print(result)
    print('------------------------------------------------------')

# >>> 執(zhí)行結果如下:
# >>> [{'name': 'Adem', 'age': 18, 'class_number': 'C', 'sex': 'boy'}]


    result = student_info.search_users(name='小')
    print(result)
    print('------------------------------------------------------')

# >>> 執(zhí)行結果如下:
# >>> ------------------------------------------------------
# >>> []
# >>> ------------------------------------------------------

    result = student_info.search_users(name='')
    print(result)
    result = student_info.search_users(name='小')
    print(result)
    print('------------------------------------------------------')
# >>> 執(zhí)行結果如下:
# >>> ------------------------------------------------------
# >>> [{'name': 'Jone', 'age': 18, 'class_number': 'A', 'sex': 'boy'}, {'name': 'Nike', 'age': 18, 'class_number': 'A', 'sex': 'boy'}, {'name': 'Lily', 'age': 18, 'class_number': 'A', 'sex': 'girl'}, {'name': 'Adem', 'age': 18, 'class_number': 'C', 'sex': 'boy'}, {'name': 'HanMeiMei', 'age': 18, 'class_number': 'B', 'sex': 'girl'}, {'name': 'Marry', 'age': 16, 'class_number': 'A', 'sex': 'girl'}]
# >>> []

    result = student_info.search_users(name='')
    print(result)

以上就是Python學習之異常斷言詳解的詳細內容,更多關于Python異常斷言的資料請關注腳本之家其它相關文章!

相關文章

  • Python+Flask實現(xiàn)自定義分頁的示例代碼

    Python+Flask實現(xiàn)自定義分頁的示例代碼

    分頁操作在web開發(fā)中幾乎是必不可少的,而flask不像django自帶封裝好的分頁操作。所以本文將自定義實現(xiàn)分頁效果,需要的可以參考一下
    2022-09-09
  • LangChain簡化ChatGPT工程復雜度使用詳解

    LangChain簡化ChatGPT工程復雜度使用詳解

    這篇文章主要為大家介紹了LangChain簡化ChatGPT工程復雜度使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-03-03
  • python壓縮和解壓縮模塊之zlib的用法

    python壓縮和解壓縮模塊之zlib的用法

    這篇文章主要介紹了python壓縮和解壓縮模塊之zlib的用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-09-09
  • Django的信號機制詳解

    Django的信號機制詳解

    Django中提供了“信號調度”,用于在框架執(zhí)行操作時解耦。通俗來講,就是一些動作發(fā)生的時候,信號允許特定的發(fā)送者去提醒一些接受者。
    2017-05-05
  • Python進程間通信Queue消息隊列用法分析

    Python進程間通信Queue消息隊列用法分析

    這篇文章主要介紹了Python進程間通信Queue消息隊列用法,結合實例形式分析了基于Queue的進程間通信相關操作技巧與使用注意事項,需要的朋友可以參考下
    2019-05-05
  • pytest官方文檔解讀之安裝和使用插件的方法

    pytest官方文檔解讀之安裝和使用插件的方法

    這篇文章主要介紹了pytest官方文檔解讀之安裝和使用插件的方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-09-09
  • python設定并獲取socket超時時間的方法

    python設定并獲取socket超時時間的方法

    今天小編就為大家分享一篇python設定并獲取socket超時時間的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-01-01
  • Python文件系統(tǒng)模塊pathlib庫

    Python文件系統(tǒng)模塊pathlib庫

    這篇文章介紹了Python中的文件系統(tǒng)模塊pathlib庫,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-05-05
  • python列表操作實例

    python列表操作實例

    這篇文章主要介紹了python列表操作方法,實例分析了Python針對列表操作的插入、刪除等各種操作技巧,需要的朋友可以參考下
    2015-01-01
  • python數(shù)據(jù)分析繪圖可視化

    python數(shù)據(jù)分析繪圖可視化

    這篇文章主要介紹了python數(shù)據(jù)分析繪圖可視化,數(shù)據(jù)可視化旨在直觀展示信息的分析結果和構思,令某些抽象數(shù)據(jù)具象化,這些抽象數(shù)據(jù)包括數(shù)據(jù)測量單位的性質或數(shù)量
    2022-06-06

最新評論