出自
https://www.cnblogs.com/alex3714/articles/5213184.html
靜態方法
通過@staticmethod裝飾器即可把其裝飾的方法變爲一個靜態方法,什麼是靜態方法呢?其實不難理解,普通的方法,可以在實例化後直接調用,並且在方法裏可以通過self.調用實例變量或類變量,但靜態方法是不可以訪問實例變量或類變量的,一個不能訪問實例變量和類變量的方法,其實相當於跟類本身已經沒什麼關係了,它與類唯一的關聯就是需要通過類名來調用這個方法
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
上面的調用會出以下錯誤,說是eat需要一個self參數,但調用時卻沒有傳遞,沒錯,當eat變成靜態方法後,再通過實例調用時就不會自動把實例本身當作一個參數傳給self了。
1 2 3 4 |
|
想讓上面的代碼可以正常工作有兩種辦法
1. 調用時主動傳遞實例本身給eat方法,即d.eat(d)
2. 在eat方法中去掉self參數,但這也意味着,在eat中不能通過self.調用實例中的其它變量了
1 class Dog(object): 2 3 def __init__(self,name): 4 self.name = name 5 6 @staticmethod 7 def eat(): 8 print(" is eating") 9 10 11 12 d = Dog("ChenRonghua") 13 d.eat()
類方法
類方法通過@classmethod裝飾器實現,類方法和普通方法的區別是, 類方法只能訪問類變量,不能訪問實例變量
1 2 3 4 5 6 7 8 9 10 11 12 |
|
執行報錯如下,說Dog沒有name屬性,因爲name是個實例變量,類方法是不能訪問實例變量的
1 2 3 4 5 6 |
|
此時可以定義一個類變量,也叫name,看下執行效果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
屬性方法
屬性方法的作用就是通過@property把一個方法變成一個靜態屬性
1 2 3 4 5 6 7 8 9 10 11 12 |
|
調用會出以下錯誤, 說NoneType is not callable, 因爲eat此時已經變成一個靜態屬性了, 不是方法了, 想調用已經不需要加()號了,直接d.eat就可以了
1 2 3 4 5 |
|
正常調用如下
1 2 3 4 5 |
|
好吧,把一個方法變成靜態屬性有什麼卵用呢?既然想要靜態變量,那直接定義成一個靜態變量不就得了麼?well, 以後你會需到很多場景是不能簡單通過 定義 靜態屬性來實現的, 比如 ,你想知道一個航班當前的狀態,是到達了、延遲了、取消了、還是已經飛走了, 想知道這種狀態你必須經歷以下幾步:
1. 連接航空公司API查詢
2. 對查詢結果進行解析
3. 返回結果給你的用戶
因此這個status屬性的值是一系列動作後纔得到的結果,所以你每次調用時,其實它都要經過一系列的動作才返回你結果,但這些動作過程不需要用戶關心, 用戶只需要調用這個屬性就可以,明白 了麼?
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") f = Flight("CA980") f.flight_status
cool , 那現在我只能查詢航班狀態, 既然這個flight_status已經是個屬性了, 那我能否給它賦值呢?試試吧
1 2 3 |
|
輸出, 說不能更改這個屬性,我擦。。。。,怎麼辦怎麼辦。。。
1 2 3 4 5 6 |
|
當然可以改, 不過需要通過@proerty.setter裝飾器再裝飾一下,此時 你需要寫一個新方法, 對這個flight_status進行更改。
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
注意以上代碼裏還寫了一個@flight_status.deleter, 是允許可以將這個屬性刪除
類的特殊成員方法
1. __doc__ 表示類的描述信息
1 2 3 4 5 6 7 8 |
|
2. __module__ 和 __class__
__module__ 表示當前操作的對象在那個模塊
__class__ 表示當前操作的對象的類是什麼
class C: def __init__(self): self.name = 'wupeiqi'
from lib.aa import C obj = C() print obj.__module__ # 輸出 lib.aa,即:輸出模塊 print obj.__class__ # 輸出 lib.aa.C,即:輸出類
3. __init__ 構造方法,通過類創建對象時,自動觸發執行。
4.__del__
析構方法,當對象在內存中被釋放時,自動觸發執行。
注:此方法一般無須定義,因爲Python是一門高級語言,程序員在使用時無需關心內存的分配和釋放,因爲此工作都是交給Python解釋器來執行,所以,析構函數的調用是由解釋器在進行垃圾回收時自動觸發執行的
5. __call__ 對象後面加括號,觸發執行。
注:構造方法的執行是由創建對象觸發的,即:對象 = 類名() ;而對於 __call__ 方法的執行是由對象後加括號觸發的,即:對象() 或者 類()()
1 2 3 4 5 6 7 8 9 10 11 12 |
|
6. __dict__ 查看類或對象中的所有成員
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
7.__str__ 如果一個類中定義了__str__方法,那麼在打印 對象 時,默認輸出該方法的返回值。
1 2 3 4 5 6 7 8 9 |
|
8.__getitem__、__setitem__、__delitem__
用於索引操作,如字典。以上分別表示獲取、設置、刪除數據
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
9. __new__ \ __metaclass__
1 2 3 4 5 6 7 8 |
|
上述代碼中,obj 是通過 Foo 類實例化的對象,其實,不僅 obj 是一個對象,Foo類本身也是一個對象,因爲在Python中一切事物都是對象。
如果按照一切事物都是對象的理論:obj對象是通過執行Foo類的構造方法創建,那麼Foo類對象應該也是通過執行某個類的 構造方法 創建。
1 2 |
|
所以,f對象是Foo類的一個實例,Foo類對象是 type 類的一個實例,即:Foo類對象 是通過type類的構造方法創建。
那麼,創建類就可以有兩種方式:
a). 普通方式
1 2 3 4 |
|
b). 特殊方式
1 2 3 4 5 6 7 |
|
def func(self): print("hello %s"%self.name) def __init__(self,name,age): self.name = name self.age = age Foo = type('Foo',(object,),{'func':func,'__init__':__init__}) f = Foo("jack",22) f.func()
So ,孩子記住,類 是由 type 類實例化產生
那麼問題來了,類默認是由 type 類實例化產生,type類中如何實現的創建類?類又是如何創建對象?
答:類中有一個屬性 __metaclass__,其用來表示該類由 誰 來實例化創建,所以,我們可以爲 __metaclass__ 設置一個type類的派生類,從而查看 類 創建的過程。
1 class MyType(type): 2 def __init__(self,*args,**kwargs): 3 4 print("Mytype __init__",*args,**kwargs) 5 6 def __call__(self, *args, **kwargs): 7 print("Mytype __call__", *args, **kwargs) 8 obj = self.__new__(self) 9 print("obj ",obj,*args, **kwargs) 10 print(self) 11 self.__init__(obj,*args, **kwargs) 12 return obj 13 14 def __new__(cls, *args, **kwargs): 15 print("Mytype __new__",*args,**kwargs) 16 return type.__new__(cls, *args, **kwargs) 17 18 print('here...') 19 class Foo(object,metaclass=MyType): 20 21 22 def __init__(self,name): 23 self.name = name 24 25 print("Foo __init__") 26 27 def __new__(cls, *args, **kwargs): 28 print("Foo __new__",cls, *args, **kwargs) 29 return object.__new__(cls) 30 31 f = Foo("Alex") 32 print("f",f) 33 print("fname",f.name)
類的生成 調用 順序依次是 __new__ --> __init__ --> __call__
metaclass 詳解文章:http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python 得票最高那個答案寫的非常好
反射
通過字符串映射或修改程序運行時的狀態、屬性、方法, 有以下4個方法
def getattr(object, name, default=None): # known special case of getattr """ getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. """ pass
判斷object中有沒有一個name字符串對應的方法或屬性
def setattr(x, y, v): # real signature unknown; restored from __doc__ """ Sets the named attribute on the given object to the specified value. setattr(x, 'y', v) is equivalent to ``x.y = v''
def delattr(x, y): # real signature unknown; restored from __doc__ """ Deletes the named attribute from the given object. delattr(x, 'y') is equivalent to ``del x.y'' """
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 2 3 4 |
|