python——物件導向相關

來源:互聯網
上載者:User

標籤:body   處理   無法   反射   test   iss   表示   資訊   異常處理   

其他相關

一、isinstance(obj, cls)

 檢查是否obj是否是類 cls 的對象

123456 class Foo(object):    passobj = Foo()isinstance(obj, Foo)

二、issubclass(sub, super)

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

1234567 class Foo(object):    passclass Bar(Foo):    passissubclass(Bar, Foo)

三、異常處理

1、異常基礎

在編程過程中為了增加友好性,在程式出現bug時一般不會將錯誤資訊顯示給使用者,而是現實一個提示的頁面,通俗來說就是不讓使用者看見大黃頁!!!

1234 try:    passexcept Exception,ex:    pass

需求:將使用者輸入的兩個數字相加

 View Code

2、異常種類

python中的異常種類非常多,每個異常專門用於處理某一項異常!!!

 常用異常 更多異常 執行個體:IndexError 執行個體:KeyError ValueError

對於上述執行個體,異常類只能用來處理指定的異常情況,如果非指定異常則無法處理。

1234567 # 未捕獲到異常,程式直接報錯s1 = ‘hello‘try:    int(s1)except IndexError,e:    print e

所以,寫程式時需要考慮到try代碼塊中可能出現的任意異常,可以這樣寫:

123456789 s1 = ‘hello‘try:    int(s1)except IndexError,e:    print eexcept KeyError,e:    print eexcept ValueError,e:    print e

萬能異常 在python的異常中,有一個萬能異常:Exception,他可以捕獲任意異常,即:

12345 s1 = ‘hello‘try:    int(s1)except Exception,e:    print e

接下來你可能要問了,既然有這個萬能異常,其他異常是不是就可以忽略了!

答:當然不是,對於特殊處理或提醒的異常需要先定義,最後定義Exception來確保程式正常運行。

123456789 s1 = ‘hello‘try:    int(s1)except KeyError,e:    print ‘鍵錯誤‘except IndexError,e:    print ‘索引錯誤‘except Exception, e:    print ‘錯誤‘

3、異常其他結構

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

4、主動觸發異常

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

5、自訂異常

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

6、斷言

12345 # assert 條件assert 1 == 1assert 1 == 2

四、反射

python中的反射功能是由以下四個內建函數提供: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‘)

詳細解析:

當我們要訪問一個對象的成員時,應該是這樣操作:

1234567891011121314 class Foo(object):    def __init__(self):        self.name = ‘alex‘    def func(self):        return ‘func‘obj = Foo()# 訪問欄位obj.name# 執行方法obj.func()
   那麼問題來了?a、上述訪問對象成員的 name 和 func 是什嗎?  答:是變數名b、obj.xxx 是什麼意思?  答:obj.xxx 表示去obj中或類中尋找變數名 xxx,並擷取對應記憶體位址中的內容。c、需求:請使用其他方式擷取obj對象中的name變數指向記憶體中的值 “alex” 問 方式一 方式二

d、比較三種訪問方式

  • obj.name
  • obj.__dict__[‘name‘]
  • getattr(obj, ‘name‘)

答:第一種和其他種比,...
      第二種和第三種比,...

 Web架構執行個體

結論:反射是通過字串的形式操作對象相關的成員。一切事物都是對象!!!

 反射當前模組成員

類也是對象

1234567891011121314151617 class Foo(object):    staticField = "old boy"    def __init__(self):        self.name = ‘wupeiqi‘    def func(self):        return ‘func‘    @staticmethod    def bar():        return ‘bar‘print getattr(Foo, ‘staticField‘)print getattr(Foo, ‘func‘)print getattr(Foo, ‘bar‘)

模組也是對象

 home.py
12345678910111213141516171819 #!/usr/bin/env python# -*- coding:utf-8 -*-"""程式目錄:    home.py    index.py當前檔案:    index.py"""import home as obj#obj.dev()func = getattr(obj, ‘dev‘)func() 
拓展:

  import 模組 (反射實現):

  a = __import__("模組名")

  a = __import__(‘lib.test.com‘, fromlist=True)

python——物件導向相關

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.