Python學習記錄day8靜態方法類方法屬性方法類的特殊成員方法1 __doc__表示類的描述信息2 __module__ 和 __class__3 __init__ 構造方法4 __del__ 析構方法5 __call__ call方法6 __dict__7 __str__ 方法8 __getitem____setitem____delitem__9 __new__ __metaclass__
上面的調用會出以下錯誤,說是eat需要一個self參數,但調用時卻沒有傳遞,沒錯,當eat變成靜態方法后,再通過實例調用時就不會自動把實例本身當作一個參數傳給self了。staticmethod.py", line 19, in <module> d.eat()TypeError: eat() missing 1 required positional argument: 'self'想讓上面的代碼可以正常工作有兩種辦法
調用時主動傳遞實例本身給eat方法,即d.eat(d) 在eat方法中去掉self參數,但這也意味著,在eat中不能通過self.調用實例中的其它變量了#!/usr/bin/env python# _*_coding:utf-8_*_''' * Created on 2017/2/27 20:18. * @author: Chinge_Yang.'''class Cat(object): def __init__(self, name): self.name = name @staticmethod # 把eat方法變為靜態方法 def eat(): # 此處去掉self print("is eating")d = Cat("bana")d.eat()2. 類方法
類方法通過@classmethod裝飾器實現,其只能訪問類變量,不能訪問實例變量。
#!/usr/bin/env python# _*_coding:utf-8_*_''' * Created on 2017/2/27 20:18. * @author: Chinge_Yang.'''class Cat(object): name = "類變量" # 需要在類中定義變量 def __init__(self, name): self.name = name @classmethod # 把eat方法變為類方法 def eat(self): # 此處有self print("%s is eating" % self.name)d = Cat("bana")d.eat()結果:實例傳入的參數不能被使用,使用的是類內部變量。因為沒有在類中定義name的話,會有錯誤提示。
類變量 is eating3. 屬性方法
屬性方法通過@property把一個方法變成一個靜態屬性。
#!/usr/bin/env python# _*_coding:utf-8_*_''' * Created on 2017/2/27 20:18. * @author: Chinge_Yang.'''class Cat(object): def __init__(self, name): self.name = name @property # 把eat方法變為屬性方法 def eat(self): print("%s is eating" % self.name)d = Cat("bana")d.eat # 此處不加括號把一個方法變成靜態屬性有什么應用場景呢? 比如 ,你想知道一個航班當前的狀態,是到達了、延遲了、取消了、還是已經飛走了, 想知道這種狀態你必須經歷以下幾步:
連接航空公司API查詢對查詢結果進行解析 返回結果給你的用戶因此這個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既然這個flight_status已經是個屬性了, 那給它賦值又如何使用呢? 需要通過@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_statusf.flight_status = 2 #觸發@flight_status.setter del f.flight_status #觸發@flight_status.deleter 注意以上代碼里還寫了一個@flight_status.deleter, 是允許可以將這個屬性刪除。
4. 類的特殊成員方法
4.1 __doc__
表示類的描述信息
class Foo: """ 描述類信息 """ def func(self): passprint(Foo.__doc__)結果:
描述類信息4.2 __module__
和 __class__
__module__
表示當前操作的對象在那個模塊
__class__
表示當前操作的對象的類是什么
cat lib/c.py
class Foo(object): def __init__(self): self.name = 'ygqygq2' cat index.py
from lib.c import Fooobj = Foo()print(obj.__module__) # 輸出 lib.c,即:輸出模塊print(obj.__class__) # 輸出 <class 'lib.c.Foo'>,即:輸出類4.3 __init__
構造方法
__init__
構造方法通過類創建對象時,自動觸發執行。
4.4 __del__
析構方法
析構方法,當對象在內存中被釋放時,自動觸發執行。
注:此方法一般無須定義,因為Python是一門高級語言,程序員在使用時無需關心內存的分配和釋放,因為此工作都是交給Python解釋器來執行,所以,析構函數的調用是由解釋器在進行垃圾回收時自動觸發執行的4.5 __call__
call方法
對象后面加括號,觸發執行。
class Foo(object): def __init__(self): pass def __call__(self, *args, **kwargs): print('__call__')obj = Foo() # 執行 __init__obj() # 執行 __call__注:構造方法的執行是由創建對象觸發的,即:對象 = 類名() ;而對于 __call__ 方法的執行是由對象后加括號觸發的,即:對象() 或者 類()()4.6 __dict__
__dict__
查看類或對象中的所有成員
class Province(object): country = 'China' def __init__(self, name, count): self.name = name self.count = count def func(self, *args, **kwargs): print('func')# 獲取類的成員,即:靜態字段、方法、print(Province.__dict__)# 輸出:{'__init__': <function Province.__init__ at 0x106a210d0>, 'country': 'China', 'func': <function Province.func at 0x106a21488>, '__doc__': None, '__dict__': <attribute '__dict__' of 'Province' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'Province' objects>}obj1 = Province('HeBei',10000)print (obj1.__dict__)# 獲取 對象obj1 的成員# 輸出:{'count': 10000, 'name': 'HeBei'}obj2 = Province('HeNan', 3888)print(obj2.__dict__)# 獲取 對象obj1 的成員# 輸出:{'count': 3888, 'name': 'HeNan'}4.7 __str__
方法
如果一個類中定義了__str__
方法,那么在打印 對象 時,默認輸出該方法的返回值。
class Foo(object): def __str__(self): return 'ygqygq2'obj = Foo()print(obj)# 輸出:ygqygq24.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'] = 'ygqygq2' # 自動觸發執行 __setitem__del obj['k1']結果:
__getitem__ k1__setitem__ k2 ygqygq2__delitem__ k1class Foo(object): def __init__(self,name): self.name = namef = Foo("ygqygq2")print(type(Foo))print(type(f))結果:
<class 'type'><class '__main__.Foo'>上述代碼中,obj 是通過 Foo 類實例化的對象,其實,不僅 obj 是一個對象,Foo類本身也是一個對象,因為在Python中一切事物都是對象。
如果按照一切事物都是對象的理論:obj對象是通過執行Foo類的構造方法創建,那么Foo類對象應該也是通過執行某個類的 構造方法 創建。
print type(f) # 輸出:<class '__main__.Foo'> 表示,obj 對象由Foo類創建print type(Foo) # 輸出:<class 'type'> 表示,Foo類對象由 type 類創建所以,f對象是Foo類的一個實例,Foo類對象是 type 類的一個實例,即:Foo類對象是通過type類的構造方法創建。 那么,創建類就可以有兩種方式: 1). 普通方式
class Foo(object): def func(self): print('hello')2). 特殊方式
def func(self): print('hello')Foo = type('Foo',(object,), {'func': func})#type第一個參數:類名#type第二個參數:當前類的基類#type第三個參數:類的成員加上構造方法,所以 ,類是由 type 類實例化產生。
那么問題來了,類默認是由 type 類實例化產生,type類中如何實現的創建類?類又是如何創建對象? 答:類中有一個屬性 __metaclass__
,其用來表示該類由誰來實例化創建,所以,我們可以為 __metaclass__
設置一個type類的派生類,從而查看類 創建的過程。 
類的生成 調用 順序依次是 __new__
–> __call__
–> __init__