Python面向對象相關


一、異常處理

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

python程序中常見的錯誤顯示信息有:

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

另外Exception可以捕獲任何異常:

s1 = 'hello'

try:

    int(s1)

except KeyError as e:

    print('鍵錯誤')

except IndexError as e:

    print('索引錯誤')

except Exception as e:

    print('錯誤')


2.異常其他結構

try:

    # 主代碼塊

    pass

except KeyError as e:

    # 異常時,執行該塊

    pass

else:

    # 主代碼塊執行完,執行該塊

    pass

finally:

    # 無論異常與否,最終執行該塊

    pass


3.自定義主動觸發異常

class SubError(Exception):      #自定義錯誤類

    def __init__(self,msg= None):

        self.msg = msg

    def __str__(self):

        if self.msg:

            return self.msg

        else:

            return 'self define error!'

try:                           # 代碼主體

    arg = 'this is a self define error!'

    raise SubError(arg)        # 主動觸發錯誤類

except Exception as e:         # e爲Exception實例化對象,錯誤信息存儲在對象中

    print(e)

4.斷言

當首要條件不滿足要求時整個程序將不會執行

a = 1           #  首要條件

try:

    assert a == 2   # 斷言首要條件是否滿足要求

    print('test')


except Exception as e:

    print('basic error:',e)


二、反射

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


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

方法一:

class Foo(object):

    def __init__(self):

        self.name = 'alex'

    def func(self):

        return 'func'

# 不允許使用 obj.name

obj = Foo()

print obj.__dict__['name']

方法二:

class Foo(object):

    def __init__(self):

        self.name = 'alex'

    def func(self):

        return 'func'

# 不允許使用 obj.name

obj = Foo()

print getattr(obj, 'name')


2.動態加載、反射操作模塊中成員

class Foo(object):

    def __init__(self,name):

        self.name = name

    def dev1(self):

        return 'this is dev1 function'


mod,cls,fun = input('url:').split('/')

module = __import__(mod)

mc = getattr(module,cls)

mcf = getattr(mc,fun)

ret = mcf('a')

print(ret)


五、單例模式

單例模式即爲單個實例模式

# ########### 單例類定義 ###########

class Foo(object):

 

    __instance = None    # 私有字段

 

    @staticmethod        # 靜態方法

    def singleton():

        if Foo.__instance:

            return Foo.__instance

        else:

            Foo.__instance = Foo()

            return Foo.__instance

 

# ########### 獲取實例 ###########

obj = Foo.singleton()

第一次調用singleton方法時實現實例化類,第二次及以後調用singleton方法時均爲同一實例,
總結:單利模式存在的目的是保證當前內存中僅存在單個實例,避免內存浪費!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章