面向對象基礎

1、isinstance(obj,cls)

檢查obj是不是類cls的對象html

class Foo(object):
    pass
obj = foo()

isinstance(obj,Foo)

2、issubclass(sub,super)

檢查sub類是不是super類的派生類python

class Foo(object):
    pass
class Bar(Foo):
    pass
issubclass(Bar, Foo)

3、異常處理

1.異常基礎

在編程過程當中爲了增長友好性,在程序出現bug時通常不會將錯誤信息顯示給用戶,而是現實一個提示的頁面,通俗來講就是不讓用戶看見大黃頁!!!編程

try:
    pass
except Exception,ex:
    pass

例:將用戶輸入的兩個數字相加函數

while True:
    num1 = raw_input('num1:')
    num2 = raw_input('num2:')
    try:
        num1 = int(num1)
        num2 = int(num2)
        result = num1 + num2
    except Exception, e:
        print '出現異常,信息以下:'
        print e

2.異常種類

Python中的異常種類很是多,每一個異常專門用於處理某一項異常!!!this

經常使用異常url

AttributeError 試圖訪問一個對象沒有的樹形,好比foo.x,可是foo沒有屬性x
IOError 輸入/輸出異常;基本上是沒法打開文件
ImportError 沒法引入模塊或包;基本上是路徑問題或名稱錯誤
IndentationError 語法錯誤(的子類) ;代碼沒有正確對齊
IndexError 下標索引超出序列邊界,好比當x只有三個元素,卻試圖訪問x[5]
KeyError 試圖訪問字典裏不存在的鍵
KeyboardInterrupt Ctrl+C被按下
NameError 使用一個還未被賦予對象的變量
SyntaxError Python代碼非法,代碼不能編譯(我的認爲這是語法錯誤,寫錯了)
TypeError 傳入對象類型與要求的不符合
UnboundLocalError 試圖訪問一個還未被設置的局部變量,基本上是因爲另有一個同名的全局變量,
致使你覺得正在訪問它
ValueError 傳入一個調用者不指望的值,即便值的類型是正確的

更多異常code

ArithmeticError
AssertionError
AttributeError
BaseException
BufferError
BytesWarning
DeprecationWarning
EnvironmentError
EOFError
Exception
FloatingPointError
FutureWarning
GeneratorExit
ImportError
ImportWarning
IndentationError
IndexError
IOError
KeyboardInterrupt
KeyError
LookupError
MemoryError
NameError
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
ReferenceError
RuntimeError
RuntimeWarning
StandardError
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError

實例IndexErrorserver

dic = ["whatmini", 'hony']
try:
    dic[10]
except IndexError, e:
    print e

實例:KeyErrorhtm

dic = {'k1':'v1'}
try:
    dic['k20']
except KeyError, e:
    print e

實例實例:ValueError對象

s1 = 'hello'
try:
    int(s1)
except ValueError, e:
    print e

對於上述實例,異常類只能用來處理指定的異常狀況,若是非指定異常則沒法處理。

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

因此,寫程序時須要考慮到try代碼塊中可能出現的任意異常,能夠這樣寫:

s1 = 'hello'
try:
    int(s1)
except IndexError,e:
    print e
except KeyError,e:
    print e
except ValueError,e:
    print e

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

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

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

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

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

三、異常其餘結構

try:
    # 主代碼塊
    pass
except KeyError,e:
    # 異常時,執行該塊
    pass
else:
    # 主代碼塊執行完,執行該塊
    pass
finally:
    # 不管異常與否,最終執行該塊
    pass

四、主動觸發異常

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

五、自定義異常

class WupeiqiException(Exception):
 
    def __init__(self, msg):
        self.message = msg
 
    def __str__(self):
        return self.message
 
try:
    raise WupeiqiException('個人異常')
except WupeiqiException,e:
    print e

六、斷言

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

4、反射

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')

詳細解析:

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

class Foo(object):
 
    def __init__(self):
        self.name = 'whatmini'
 
    def func(self):
        return 'func'
 
obj = Foo()
 
# 訪問字段
obj.name
# 執行方法
obj.func()

那麼問題來了?

a、上述訪問對象成員的 name 和 func 是什麼?

答:是變量名

b、obj.xxx 是什麼意思?

答:obj.xxx 表示去obj中或類中尋找變量名 xxx,並獲取對應內存地址中的內容。

c、需求:請使用其餘方式獲取obj對象中的name變量指向內存中的值 「whatmini」

class Foo(object):
 
    def __init__(self):
        self.name = 'whatmini'
 
# 不容許使用 obj.name
obj = Foo()

方式一

class Foo(object):

    def __init__(self):
        self.name = 'whatmini'

    def func(self):
        return 'func'

# 不容許使用 obj.name
obj = Foo()

print obj.__dict__['name']

方式二

class Foo(object):

    def __init__(self):
        self.name = 'whatmini'

    def func(self):
        return 'func'

# 不容許使用 obj.name
obj = Foo()

print getattr(obj, 'name')

d、比較三種訪問方式

  • obj.name

  • obj.__dict__['name']

  • getattr(obj, 'name')

    #!/usr/bin/env python
    #coding:utf-8
    from wsgiref.simple_server import make_server

    class Handler(object):

    def index(self):
           return 'index'
    
       def news(self):
           return 'news'

    def RunServer(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    url = environ['PATH_INFO']
    temp = url.split('/')[1]
    obj = Handler()
    is_exist = hasattr(obj, temp)
    if is_exist:
    func = getattr(obj, temp)
    ret = func()
    return ret
    else:
    return '404 not found'

    if name == 'main':
    httpd = make_server('', 8001, RunServer)
    print "Serving HTTP on port 8000..."
    httpd.serve_forever()

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

反射當前模塊成員

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import sys


def s1():
    print 's1'


def s2():
    print 's2'


this_module = sys.modules[__name__]

hasattr(this_module, 's1')
getattr(this_module, 's2')

類也是對象

class Foo(object):
 
    staticField = "創世紀"
 
    def __init__(self):
        self.name = 'whatmini'
 
    def func(self):
        return 'func'
 
    @staticmethod
    def bar():
        return 'bar'
 
print getattr(Foo,'staticField')
print getattr(Foo,'func')
print getattr(Foo,'bar')

模塊也是對象

#!/usr/bin/env python
# -*- coding:utf-8 -*-

def dev():
    return 'dev'

例:

#!/usr/bin/env python
    # -*- coding:utf-8 -*-
 
    """
    程序目錄:
        home.py
        index.py
     
    當前文件:
        index.py
    """
     
     
    import home as obj
     
    #obj.dev()
     
    func = getattr(obj, 'dev')
    func()
相關文章
相關標籤/搜索