python 入門第七課 面向物件進階
靜態方法:
@staticmethod,只是名義上歸類管理,實際上在靜態方法裡訪問不了類或者例項的任何屬性
類方法:
@classmethod,只能訪問類變數,不能訪問例項變數
屬性方法:
@property ,把一個方法變成一個靜態屬性
屬性方法的應用如下: f.flight_status呼叫屬性方法,.setter 進行修改,.deleter進行刪除
__author__ = 'admin' class Flight(object): def __init__(self,name): self.flight_name = name def checking_status(self): print("checking flight %s status " % self.flight_name) return 1 @property def flight_status(self): status = self.checking_status() if status == 0 : print("flight got canceled...") elif status == 1 : print("flight is arrived...") elif status == 2: print("flight has departured already...") else: print("cannot confirm the flight status...,please check later") @flight_status.setter #修改 def flight_status(self,status): status_dic = { 0 : "canceled", 1 :"arrived", 2 : "departured" } print("\033[31;1mHas changed the flight status to \033[0m",status_dic.get(status) ) @flight_status.deleter #刪除 def flight_status(self): print("status got removed...") f = Flight("CA980") f.flight_status f.flight_status = 2 #觸發@flight_status.setter del f.flight_status #觸發@flight_status.deleter
執行結果如下:
checking flight CA980 status
flight is arrived...
Has changed the flight status to departured
status got removed...
類的特殊成員方法
1.1 1. doc 表示類的描述資訊
class Foo:
""" 描述類資訊,這是用於看片的神奇 """
def func(self):
pass
print Foo.__doc__
輸出:類的描述資訊
1.2 module 和 class 表示當前操作的物件在那個模組 和表示當前操作的物件的類是什麼
from lib.aa import C
obj = C()
print (obj.__module__ ) # 輸出 lib.aa,即:輸出模組
print (obj.__class__ ) # 輸出 lib.aa.C,即:輸出類
1.3. init 構造方法,通過類建立物件時,自動觸發執行。
1.4. del 析構方法,當物件在記憶體中被釋放時,自動觸發執行。
1.5. call 物件後面加括號,觸發執行。需要先定義__call__方法
class Foo:
def __init__(self): pass def __call__(self, *args, **kwargs): print '__call__'
obj = Foo() # 執行 init
obj() # 執行 call
1.6 . dict 檢視類或物件中的所有成員
print(Foo.__dict__) 返回類的屬性
print(obj.__dict__) 返回例項的屬性
1.7 str 如果一個類中定義了__str__方法,那麼在列印 物件 時,預設輸出該方法的返回值。
class Foo:
def str(self):
return 'alex li'
obj = Foo()
print( obj )
輸出:alex li
1.8.__getitem__、setitem、delitem 需要先定義它們的方法
class Foo(object):
def __getitem__(self, key):
print('__getitem__',key)
def __setitem__(self, key, value):
print('__setitem__',key,value)
def __delitem__(self, key):
print('__delitem__',key)
obj = Foo()
result = obj['k1'] # 自動觸發執行 getitem
obj['k2'] = 'alex' # 自動觸發執行 setitem
del obj['k1']
1.9 new metaclass #方法__new__用來例項化物件 , metaclass,其用來表示該類由 誰 來例項化建立,可以為 metaclass 設定一個type類的派生類,從而檢視 類 建立的過程:類的生成 呼叫 順序依次是 MyType.__init__ -->MyType.__call__ --> Foo.__new__ --> Foo.__init__
類class Foo的特殊定義方法:
def func(self):
print 'hello wupeiqi'
Foo = type('Foo',(object,), {'func': func})
type第一個引數:類名
type第二個引數:當前類的基類
type第三個引數:類的成員
class MyType(type):
def init(self,*args,**kwargs):
print("Mytype __init__",*args,**kwargs)
def __call__(self, *args, **kwargs):
print("Mytype __call__", *args, **kwargs)
obj = self.__new__(self)
print("obj ",obj,*args, **kwargs)
print(self)
self.__init__(obj,*args, **kwargs)
return obj
def __new__(cls, *args, **kwargs):
print("Mytype __new__",*args,**kwargs)
return type.__new__(cls, *args, **kwargs)
print('here...')
class Foo(object,metaclass=MyType):
#metaclass = MyType
def __init__(self,name):
self.name = name
print("Foo __init__")
def __new__(cls, *args, **kwargs):
print("Foo __new__",cls, *args, **kwargs)
return object.__new__(cls)
f = Foo("Alex")
print("f",f)
print("fname",f.name)
1.10 反射
hasattr(obj,y) 判斷物件是否有屬性'y',返回True或False
getattr(obj,y) 獲取物件方法y的地址或者屬性y的值
setattr(obj,y,v) 設定物件的obj.y=v
delattr(obj,y) 刪除物件的屬性y
__author__ = 'admin'
def eat(self):
print('eating')
class Foo(object):
def __init__(self):
self.name = 'wupeiqi'
def func(self):
return 'func'
choice = input('>>:').strip()
d = Foo()
if hasattr(d,choice):
attr = getattr(d,choice)
print(attr())
else:
setattr(d,choice,eat) #add new attr 'eat'
getattr(d,choice)(d) #將obj本身作為方法eat的引數進行呼叫
# setattr(d,choice,"name1") #新增屬性 d.choice = 'name1'
# print(hasattr(d,choice))
# print(getattr(d,choice)) #getattr(d,choice)直接新增的屬性的值
2 異常處理
2.1 異常提示
try:
#s1 = 'hello'
#int(s1)
name = []
name[2]
except IndexError as e:
print(e)
except KeyError as e:
print(e)
except ValueError as e:
print(e)
except Exception as e :
print(e)
else:
print('unknown error')
finally:
print(66)
2.2 自定義異常,主動觸發
class WupeiqiException(Exception):
def __init__(self, msg):
self.message = msg
def __str__(self):
return self.message
try:
raise WupeiqiException('我的異常')
except WupeiqiException as e:
print(e)