經過@staticmethod裝飾器便可把其裝飾的方法變爲一個靜態方法,什麼是靜態方法呢?其實不難理解,普通的方法,能夠在實例化後直接調用,而且在方法裏能夠經過self.調用實例變量或類變量,但靜態方法是不能夠訪問實例變量或類變量的,一個不能訪問實例變量和類變量的方法,其實至關於跟類自己已經沒什麼關係了,它與類惟一的關聯就是須要經過類名來調用這個方法。python
class Dog(object): def __init__(self,name): self.name = name @staticmethod #把eat方法變爲靜態方法
def eat(self): print("%s is eating" % self.name) d = Dog("ChenRonghua") d.eat()
上面的調用會出如下錯誤,說是eat須要一個self參數,但調用時卻沒有傳遞,沒錯,當eat變成靜態方法後,再經過實例調用時就不會自動把實例自己看成一個參數傳給self了。程序員
Traceback (most recent call last): File "/Users/PycharmProjects/python基礎/靜態方法.py", line 17, in <module> d.eat() TypeError: eat() missing 1 required positional argument: 'self'
想讓上面的代碼能夠正常工做有兩種辦法編程
1. 調用時主動傳遞實例自己給eat方法,即d.eat(d) 服務器
2. 在eat方法中去掉self參數,但這也意味着,在eat中不能經過self.調用實例中的其它變量了函數
class Dog(object): def __init__(self,name): self.name = name @staticmethod def eat(): print(" is eating") d = Dog("ChenRonghua") d.eat()
類方法經過@classmethod裝飾器實現,類方法和普通方法的區別是, 類方法只能訪問類變量,不能訪問實例變量ui
class Dog(object): def __init__(self,name): self.name = name @classmethod def eat(self): print("%s is eating" % self.name) d = Dog("LJ") d.eat()
執行報錯以下,說Dog沒有name屬性,由於name是個實例變量,類方法是不能訪問實例變量的this
Traceback (most recent call last): File "/Users/類方法.py", line 16, in <module> d.eat() File "/Users/類方法.py", line 11, in eat print("%s is eating" % self.name) AttributeError: type object 'Dog' has no attribute 'name'
此時能夠定義一個類變量,也叫name,看下執行效果spa
class Dog(object): name = "我是類變量"
def __init__(self,name): self.name = name @classmethod def eat(self): print("%s is eating" % self.name) d = Dog("ChenRonghua") d.eat() #執行結果 我是類變量 is eating
屬性方法的做用就是經過@property把一個方法變成一個靜態屬性。設計
class Dog(object): def __init__(self,name): self.name = name @property def eat(self): print(" %s is eating" %self.name) d = Dog("LJ") d.eat()
調用會出如下錯誤, 說NoneType is not callable, 由於eat此時已經變成一個靜態屬性了, 不是方法了, 想調用已經不須要加()號了,直接d.eat就能夠了code
Traceback (most recent call last): ChenRonghua is eating File "/Users/屬性方法.py", line 16, in <module> d.eat() TypeError: 'NoneType' object is not callable
正常調用以下
d = Dog("LJ") d.eat 輸出 LJ is eating
好吧,把一個方法變成靜態屬性有什麼卵用呢?既然想要靜態變量,那直接定義成一個靜態變量不就得了麼?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
那如今我能查詢航班狀態, 既然這個flight_status已是個屬性了, 那我可否給它賦值呢?
f = Flight("CA980") f.flight_status f.flight_status = 2
輸出報錯
checking flight CA980 status flight is arrived... Traceback (most recent call last): File "/Users/屬性方法.py", line 58, in <module> f.flight_status = 2 AttributeError: can't set attribute
固然能夠改, 不過須要經過@property.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, 是容許能夠將這個屬性刪除。
表示類的描述信息
class Foo: """ 描述類信息 """
def func(self): pass
print(Foo.__doc__) #輸出:類的描述信息
__module__ 表示當前操做的對象在哪一個模塊
__class__ 表示當前操做的對象的類是什麼
#lib/aa.py
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,即:輸出類
構造方法,經過類建立對象時,自動觸發執行。
析構方法,當對象在內存中被釋放時,自動觸發執行。
注:此方法通常無須定義,由於Python是一門高級語言,程序員在使用時無需關心內存的分配和釋放,由於此工做都是交給Python解釋器來執行,因此,析構函數的調用是由解釋器在進行垃圾回收時自動觸發執行的.
對象後面加括號,觸發執行。
注:構造方法的執行是由建立對象觸發的,即:對象 = 類名() ;而對於 __call__ 方法的執行是由對象後加括號觸發的,即:對象() 或者 類()()
class Foo: def __init__(self): pass
def __call__(self, *args, **kwargs): print '__call__' obj = Foo() # 執行 __init__
obj() # 執行 __call__
查看類或對象中的全部成員。
class Province: country = 'China'
def __init__(self, name, count): self.name = name self.count = count def func(self, *args, **kwargs): print 'func'
# 獲取類的成員,即:靜態字段、方法、
print Province.__dict__
# 輸出:{'country': 'China', '__module__': '__main__', 'func': <function func at 0x10be30f50>, '__init__': <function __init__ at 0x10be30ed8>, '__doc__': None}
obj1 = Province('HeBei',10000) print obj1.__dict__
# 獲取 對象obj1 的成員 # 輸出:{'count': 10000, 'name': 'HeBei'}
obj2 = Province('HeNan', 3888) print obj2.__dict__
# 獲取 對象obj1 的成員 # 輸出:{'count': 3888, 'name': 'HeNan'}
若是一個類中定義了__str__方法,那麼在打印 對象 時,默認輸出該方法的返回值。
class Foo: def __str__(self): return 'li' obj = Foo() print obj # 輸出:li
用於索引操做,如字典。以上分別表示獲取、設置、刪除數據。
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']
class Foo(object): def __init__(self,name): self.name = name f = Foo("alex")
上述代碼中,obj 是經過 Foo 類實例化的對象,其實,不只 obj 是一個對象,Foo類自己也是一個對象,由於在Python中一切事物都是對象。
若是按照一切事物都是對象的理論:obj對象是經過執行Foo類的構造方法建立,那麼Foo類對象應該也是經過執行某個類的 構造方法 建立。
print type(f) # 輸出:<class '__main__.Foo'> 表示,obj 對象由Foo類建立
print type(Foo) # 輸出:<type 'type'> 表示,Foo類對象由 type 類建立
因此,f 對象是Foo類的一個實例,Foo類對象是 type 類的一個實例,即:Foo類對象 是經過type類的構造方法建立。
那麼,建立類就能夠有兩種方式:
a.普通方式:
class Foo(object): def func(self): print(hello)
b.特殊方式
def func(self): print 'hello wupeiqi' Foo = type('Foo',(object,), {'func': func}) #type第一個參數:類名 #type第二個參數:當前類的基類 #type第三個參數:類的成員
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類的派生類,從而查看 類 建立的過程。
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): 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)
類的生成 調用 順序依次是 __new__ --> __init__ --> __call__
metaclass 詳解文章:http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python 得票最高那個答案寫的很是好
反射的概念是由Smith在1982年首次提出的,主要是指程序能夠訪問、檢測和修改它自己狀態或行爲的一種能力(自省)。這一律唸的提出很快引起了計算機科學領域關於應用反射性的研究。它首先被程序語言的設計領域所採用,並在Lisp和麪向對象方面取得了成績。
經過字符串的形式操做對象相關的屬性。python中的一切事物都是對象(均可以使用反射)
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')
詳細解析:當咱們要訪問一個對象的成員時,應該是這樣操做:
class Foo(object): def __init__(self): self.name = 'alex'
def func(self): return 'func' obj = Foo() # 訪問字段
obj.name # 執行方法
obj.func()
class Foo(object): def __init__(self): self.name = 'alex'
# 不容許使用 obj.name
obj = Foo()
答:有兩種方式,以下:
#方式1
class Foo(object): def __init__(self): self.name = 'alex'
def func(self): return 'func'
# 不容許使用 obj.name
obj = Foo() print obj.__dict__['name']
#方式2:
class Foo(object): def __init__(self): self.name = 'alex'
def func(self): return 'func'
# 不容許使用 obj.name
obj = Foo() print getattr(obj, 'name')
結論:反射是經過字符串的形式操做對象相關的成員。一切事物都是對象!!!
#反射當前模塊成員
#!/usr/bin/env python # -*- coding:utf-8 -*-
import sys def s1(): print('s1') def s2(): print('s2')
this_module = sys.modules[__name__] print(hasattr(this_module, 's1')) print(getattr(this_module, 's2')) #輸出 #True #<function s2 at 0x0000026D6476E1E0>
類也是對象
class Foo(object): staticField = "AAA"
def __init__(self): self.name = 'wupeiqi'
def func(self): return 'func' @staticmethod def bar(): return 'bar'
print(getattr(Foo, 'staticField')) print(getattr(Foo, 'func')) print(getattr(Foo, 'bar')) #輸出: # AAA # <function Foo.func at 0x0000021A3D21E268> # <function Foo.bar at 0x0000021A3D21E2F0>
模塊也是對象
#!/usr/bin/env python # -*- coding:utf-8 -*-
def dev(): return 'dev'
#!/usr/bin/env python # -*- coding:utf-8 -*-
""" 程序目錄: home.py index.py 當前文件: index.py """
import home as obj #obj.dev()
func = getattr(obj, 'dev') func()
好處一:實現可插拔機制
有倆程序員,一個A,一個是B,A在寫程序的時候須要用到B所寫的類,可是B去跟女友度蜜月去了,尚未完成他寫的類,A想到了反射,使用了反射機制A能夠繼續完成本身的代碼,等B度蜜月回來後再繼續完成類的定義而且去實現A想要的功能。
總之反射的好處就是,能夠事先定義好接口,接口只有在被完成後纔會真正執行,這實現了即插即用,這實際上是一種‘後期綁定’,什麼意思?即你能夠事先把主要的邏輯寫好(只定義接口),而後後期再去實現接口的功能
#B尚未實現的功能 class FtpClient: 'ftp客戶端,可是還麼有實現具體的功能' def __init__(self,addr): print('正在鏈接服務器[%s]' %addr) self.addr=addr
#不影響A的開發
#from module import FtpClient
f1=FtpClient('192.168.1.1') if hasattr(f1,'get'): func_get=getattr(f1,'get') func_get() else: print('---->不存在此方法') print('處理其餘的邏輯')
好處二:動態導入模塊(基於反射當前模塊成員)
在編程過程當中爲了增長友好性,在程序出現bug時通常不會將錯誤信息顯示給用戶,而是現實一個提示的頁面,通俗來講就是不讓用戶看見大黃頁!!!
try: pass
except Exception: pass
需求:將用戶輸入的兩個數字相加
while True: num1 = input('num1:') num2 = input('num2:') try: num1 = int(num1) num2 = int(num2) result = num1 + num2 except Exception as e: print('出現異常,信息以下:') print(e)
python中的異常種類很是多,每一個異常專門用於處理某一項異常!!!
經常使用異常:
AttributeError 試圖訪問一個對象沒有的樹形,好比foo.x,可是foo沒有屬性x
IOError 輸入/輸出異常;基本上是沒法打開文件
ImportError 沒法引入模塊或包;基本上是路徑問題或名稱錯誤
IndentationError 語法錯誤(的子類) ;代碼沒有正確對齊
IndexError 下標索引超出序列邊界,好比當x只有三個元素,卻試圖訪問x[5]
KeyError 試圖訪問字典裏不存在的鍵
KeyboardInterrupt Ctrl+C被按下
NameError 使用一個還未被賦予對象的變量
SyntaxError Python代碼非法,代碼不能編譯(我的認爲這是語法錯誤,寫錯了)
TypeError 傳入對象類型與要求的不符合
UnboundLocalError 試圖訪問一個還未被設置的局部變量,基本上是因爲另有一個同名的全局變量,致使你覺得正在訪問它
ValueError 傳入一個調用者不指望的值,即便值的類型是正確的
寫程序時須要考慮到try代碼塊中可能出現的任意異常,能夠這樣寫:
s1 = 'hello'
try: int(s1) except IndexError as e: print(e) except KeyError as e: print(e) except ValueError as e: print(e)
萬能異常 在python的異常中,有一個萬能異常:Exception,他能夠捕獲任意異常,即:
s1 = 'hello'
try: int(s1) except Exception as e: print(e)
接下來你可能要問了,既然有這個萬能異常,其餘異常是否是就能夠忽略了!
答:固然不是,對於特殊處理或提醒的異常須要先定義,最後定義Exception來確保程序正常運行。
s1 = 'hello'
try: int(s1) except KeyError as e: print('鍵錯誤') except IndexError as e: print('索引錯誤') except Exception as e: print('錯誤')
try: # 主代碼塊
pass
except KeyError as e: # 異常時,執行該塊
pass
else: # 主代碼塊執行完,執行該塊
pass
finally: # 不管異常與否,最終執行該塊
pass
try: raise Exception('錯誤了。。。') except Exception as e: print e
class YL_Exception(Exception): def __init__(self, msg): self.message = msg def __str__(self): return self.message try: raise YL_Exception('個人異常') except YL_Exception as e: print(e)
assert 1 == 1
assert 1 == 2
# 輸出: # Traceback (most recent call last): # File "test.py", line 185, in <module> # assert 1 == 2 # AssertionError
assert 2==1,'2不等於1'
# 輸出 # Traceback (most recent call last): # File "test.py", line 188, in <module> # assert 2==1,'2不等於1' # AssertionError: 2不等於1