靜態方法:
@staticmethod,只是名義上歸類管理,實際上在靜態方法裏訪問不了類或者實例的任何屬性
類方法:
@classmethod,只能訪問類變量,不能訪問實例變量
屬性方法:
@property ,把一個方法變成一個靜態屬性
屬性方法的應用以下: f.flight_status調用屬性方法,.setter 進行修改,.deleter進行刪除code
__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:
""" 描述類信息,這是用於看片的神奇 """blog
def func(self): pass
print Foo.__doc__ip
1.2 module 和 class 表示當前操做的對象在那個模塊 和表示當前操做的對象的類是什麼
from lib.aa import C內存
obj = C()
print (obj.__module__ ) # 輸出 lib.aa,即:輸出模塊
print (obj.__class__ ) # 輸出 lib.aa.C,即:輸出類rem
1.3. init 構造方法,經過類建立對象時,自動觸發執行。
1.4. del 析構方法,當對象在內存中被釋放時,自動觸發執行。
1.5. call 對象後面加括號,觸發執行。須要先定義__call__方法
class Foo:get
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__) 返回實例的屬性input
1.7 str 若是一個類中定義了__str__方法,那麼在打印 對象 時,默認輸出該方法的返回值。
class Foo:
def str(self):
return 'alex li'
obj = Foo()
print( obj )it
1.8.__getitem__、setitem、delitem 須要先定義它們的方法io
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})
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)