class8-再識物件導向

來源:互聯網
上載者:User

標籤:

一、isinstance(obj,cls)

檢查obj是否是cls類的對象,返回布爾值

class Foo(object):    passobj = Foo()ret = isinstance(obj,Foo)
print ret
True

 

二、issubclass(sub, super)

檢查sub類是否是super的衍生類別

class Foo(object):    passclass Bar(Foo):    passret = issubclass(Bar, Foo)
print ret
True

 

三、異常處理

常用異常

AttributeError 試圖訪問一個對象沒有的樹形,比如foo.x,但是foo沒有屬性xIOError 輸入/輸出異常;基本上是無法開啟檔案ImportError 無法引入模組或包;基本上是路徑問題或名稱錯誤IndentationError 語法錯誤(的子類) ;代碼沒有正確對齊IndexError 下標索引超出序列邊界,比如當x只有三個元素,卻試圖訪問x[5]KeyError 試圖訪問字典裡不存在的鍵KeyboardInterrupt Ctrl+C被按下NameError 使用一個還未被賦予對象的變數SyntaxError Python代碼非法,代碼不能編譯(個人認為這是語法錯誤,寫錯了)TypeError 傳入物件類型與要求的不符合UnboundLocalError 試圖訪問一個還未被設定的局部變數,基本上是由於另有一個同名的全域變數,導致你以為正在訪問它ValueError 傳入一個調用者不期望的值,即使值的類型是正確的

更多異常

ArithmeticErrorAssertionErrorAttributeErrorBaseExceptionBufferErrorBytesWarningDeprecationWarningEnvironmentErrorEOFErrorExceptionFloatingPointErrorFutureWarningGeneratorExitImportErrorImportWarningIndentationErrorIndexErrorIOErrorKeyboardInterruptKeyErrorLookupErrorMemoryErrorNameErrorNotImplementedErrorOSErrorOverflowErrorPendingDeprecationWarningReferenceErrorRuntimeErrorRuntimeWarningStandardErrorStopIterationSyntaxErrorSyntaxWarningSystemErrorSystemExitTabErrorTypeErrorUnboundLocalErrorUnicodeDecodeErrorUnicodeEncodeErrorUnicodeErrorUnicodeTranslateErrorUnicodeWarningUserWarningValueErrorWarningZeroDivisionError

萬能異常處理模組

Exception

異常完整結構

try:    # 主代碼塊    passexcept KeyError,e:    # 異常時,執行該塊    passelse:    # 主代碼塊執行完,執行該塊    passfinally:    # 無論異常與否,最終執行該塊    pass

主動觸發異常:raise

try:    raise Exception(‘錯誤了。。。‘)except Exception,e:    print e

自訂異常

拿異常KeyEerror說明:通過查看源碼得知,KeyError的基類為Exception,而且Exception 是所有異常的基類,故我們可以自訂異常,讓其繼承Exception類即可,如:

class MyException(Exception):    def __init__(self, msg):        self.message = msg    def __str__(self):        return self.messagetry:    raise MyException(‘我的異常‘)except MyException,e:    print e

斷言

assert條件

Python中assert用來判斷語句的真假,如果為假的話將觸發AssertionError錯誤

a = 23a -= 1assert a == 23  #此時條件為False,報AssertionError 錯誤#############Traceback (most recent call last):  File "D:/py-project/test/test11.py", line 5, in <module>    assert a == 23AssertionError#############

四、反射

python中的反射功能是由以下四個內建函數提供:hasattr、getattr、setattr、delattr

改四個函數分別用於對對象內部執行:hasattr  檢查是否含有某成員getattr   擷取成員setattr   設定成員delattr    刪除成員class Foo(object):    def __init__(self):        self.name = ‘wupeiqi‘    def func(self):        return ‘func‘obj = Foo()# #### 檢查是否含有成員 #### hasattr(obj, ‘name‘)hasattr(obj, ‘func‘)# #### 擷取成員 #### getattr(obj, ‘name‘)getattr(obj, ‘func‘)# #### 設定成員 #### setattr(obj, ‘age‘, 18)setattr(obj, ‘show‘, lambda num: num + 1)# #### 刪除成員 #### delattr(obj, ‘name‘)delattr(obj, ‘func‘)

class8-再識物件導向

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.