Skip to Content
Python 技術手冊 第三版
book

Python 技術手冊 第三版

by lex Martelli, Anna Martelli Ravenscroft, Steve Holden
January 2018
Intermediate to advanced
856 pages
17h 17m
Chinese
GoTop Information, Inc.
Content preview from Python 技術手冊 第三版
190
|
5 章 例外
自訂的例外類別
你可以擴充任何的標準例外類別來定義你自己的例外類別。通常,這樣的
子類別除了加上一個 docstring 以外不會做任何事:
class InvalidAttribute(AttributeError):
"""Used to indicate attributes that could never be valid"""
任何空的類別或函式都應該有一個
docstring
而非
pass
如前面的「pass 述句」中所涵蓋的,你不需要一個
pass
述句來構成一個類別的主體,只要有 docstring(你應該永
遠都寫,以記載類別的用途)就足以讓 Python 滿意。所
有「空」類別(不管它們是不是例外類別)的最佳實務做
法,就跟所有「空」函式一樣,都是帶有一個 docstring
而非
pass
述句。
根據
try/except
的語意,提出像
InvalidAttribute
這樣的自訂例外類別幾
乎等同於提出它的標準例外超類別
AttributeError
。處理
AttributeError
任何
except
子句也都能處理
InvalidAttribute
。此外,知道你自訂例外類
InvalidAttribute
的客戶端程式碼也能特別處理它,而不用應付不準備
處理的其他 AttributeError 情況。舉例來說:
class SomeFunkyClass(object):
"""much hypothetical functionality snipped"""
def ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

利用 Python 进行数据分析(原书第2版)

利用 Python 进行数据分析(原书第2版)

Wes McKinney

Publisher Resources

ISBN: 9789864766819