類的成員python
類的成員能夠分爲三大類:字段、方法和屬性程序員
注:全部成員中,只有普通字段的內容保存對象中,即:根據此類建立了多少對象,在內存中就有多少個普通字段。而其餘的成員,則都是保存在類中,即:不管對象的多少,在內存中只建立一份。數據庫
1、字段cookie
字段包括:普通字段和靜態字段,他們在定義和使用中有所區別,而最本質的區別是內存中保存的位置不一樣,框架
1 class Province: 2 3 # 靜態字段 4 country = '中國' 5 6 def __init__(self, name): 7 8 # 普通字段 9 self.name = name 10 11 12 # 直接訪問普通字段 13 obj = Province('河北省') 14 print obj.name 15 16 # 直接訪問靜態字段 17 Province.country
由上述代碼能夠看出【普通字段須要經過對象來訪問】【靜態字段經過類訪問】,在使用上能夠看出普通字段和靜態字段的歸屬是不一樣的。其在內容的存儲方式相似以下圖:less
由上圖可知:函數
靜態字段在內存中只保存一份post
普通字段在每一個對象中都要保存一份this
應用場景: 經過類建立對象時,若是每一個對象都具備相同的字段,那麼就使用靜態字段url
2、方法
方法包括:普通方法、靜態方法和類方法,三種方法在內存中都歸屬於類,區別在於調用方式不一樣。
1 class Foo: 2 3 def __init__(self, name): 4 self.name = name 5 6 def ord_func(self): 7 """ 定義普通方法,至少有一個self參數 """ 8 9 # print self.name 10 print '普通方法' 11 12 @classmethod 13 def class_func(cls): 14 """ 定義類方法,至少有一個cls參數 """ 15 16 print '類方法' 17 18 @staticmethod 19 def static_func(): 20 """ 定義靜態方法 ,無默認參數""" 21 22 print '靜態方法' 23 24 25 # 調用普通方法 26 f = Foo() 27 f.ord_func() 28 29 # 調用類方法 30 Foo.class_func() 31 32 # 調用靜態方法 33 Foo.static_func()
相同點:對於全部的方法而言,均屬於類(非對象)中,因此,在內存中也只保存一份。
不一樣點:方法調用者不一樣、調用方法時自動傳入的參數不一樣。
3、屬性
若是你已經瞭解Python類中的方法,那麼屬性就很是簡單了,由於Python中的屬性實際上是普通方法的變種。
對於屬性,有如下三個知識點:
屬性的基本使用
屬性的兩種定義方式
一、屬性的基本使用
1 # ############### 定義 ############### 2 class Foo: 3 4 def func(self): 5 pass 6 7 # 定義屬性 8 @property 9 def prop(self): 10 pass 11 # ############### 調用 ############### 12 foo_obj = Foo() 13 14 foo_obj.func() 15 foo_obj.prop #調用屬性
由屬性的定義和調用要注意一下幾點:
定義時,在普通方法的基礎上添加 @property 裝飾器;
定義時,屬性僅有一個self參數
調用時,無需括號
方法:foo_obj.func()
屬性:foo_obj.prop
注意:屬性存在乎義是:訪問屬性時能夠製造出和訪問字段徹底相同的假象
屬性由方法變種而來,若是Python中沒有屬性,方法徹底能夠代替其功能。
實例:對於主機列表頁面,每次請求不可能把數據庫中的全部內容都顯示到頁面上,而是經過分頁的功能局部顯示,因此在向數據庫中請求數據時就要顯示的指定獲取從第m條到第n條的全部數據(即:limit m,n),這個分頁的功能包括:
1 # ############### 定義 ############### 2 class Pager: 3 4 def __init__(self, current_page): 5 # 用戶當前請求的頁碼(第一頁、第二頁...) 6 self.current_page = current_page 7 # 每頁默認顯示10條數據 8 self.per_items = 10 9 10 11 @property 12 def start(self): 13 val = (self.current_page - 1) * self.per_items 14 return val 15 16 @property 17 def end(self): 18 val = self.current_page * self.per_items 19 return val 20 21 # ############### 調用 ############### 22 23 p = Pager(1) 24 p.start 就是起始值,即:m 25 p.end 就是結束值,即:n
從上述可見,Python的屬性的功能是:屬性內部進行一系列的邏輯計算,最終將計算結果返回。
二、屬性的兩種定義方式
屬性的定義有兩種方式:
裝飾器 即:在方法上應用裝飾器
靜態字段 即:在類中定義值爲property對象的靜態字段
裝飾器方式:在類的普通方法上應用@property裝飾器
咱們知道Python中的類有經典類和新式類,新式類的屬性比經典類的屬性豐富。( 若是類繼object,那麼該類是新式類 )
經典類,具備一種@property裝飾器(如上一步實例)
1 # ############### 定義 ############### 2 class Goods: 3 4 @property 5 def price(self): 6 return "wupeiqi" 7 # ############### 調用 ############### 8 obj = Goods() 9 result = obj.price # 自動執行 @property 修飾的 price 方法,並獲取方法的返回值
新式類,具備三種@property裝飾器
# ############### 定義 ############### class Goods(object): @property def price(self): print '@property' @price.setter def price(self, value): print '@price.setter' @price.deleter def price(self): print '@price.deleter' # ############### 調用 ############### obj = Goods() obj.price # 自動執行 @property 修飾的 price 方法,並獲取方法的返回值 obj.price = 123 # 自動執行 @price.setter 修飾的 price 方法,並將 123 賦值給方法的參數 del obj.price # 自動執行 @price.deleter 修飾的 price 方法
注:經典類中的屬性只有一種訪問方式,其對應被 @property 修飾的方法
新式類中的屬性有三種訪問方式,並分別對應了三個被@property、@方法名.setter、@方法名.deleter修飾的方法
因爲新式類中具備三種訪問方式,咱們能夠根據他們幾個屬性的訪問特色,分別將三個方法定義爲對同一個屬性:獲取、修改、刪除
1 class Goods(object): 2 3 def __init__(self): 4 # 原價 5 self.original_price = 100 6 # 折扣 7 self.discount = 0.8 8 9 @property 10 def price(self): 11 # 實際價格 = 原價 * 折扣 12 new_price = self.original_price * self.discount 13 return new_price 14 15 @price.setter 16 def price(self, value): 17 self.original_price = value 18 19 @price.deltter 20 def price(self, value): 21 del self.original_price 22 23 obj = Goods() 24 obj.price # 獲取商品價格 25 obj.price = 200 # 修改商品原價 26 del obj.price # 刪除商品原價
靜態字段方式,建立值爲property對象的靜態字段
當使用靜態字段的方式建立屬性時,經典類和新式類無區別
1 class Foo: 2 3 def get_bar(self): 4 return 'wupeiqi' 5 6 BAR = property(get_bar) 7 8 obj = Foo() 9 reuslt = obj.BAR # 自動調用get_bar方法,並獲取方法的返回值 10 print reuslt
property的構造方法中有個四個參數
第一個參數是方法名,調用 對象.屬性 時自動觸發執行方法
第二個參數是方法名,調用 對象.屬性 = XXX 時自動觸發執行方法
第三個參數是方法名,調用 del 對象.屬性 時自動觸發執行方法
第四個參數是字符串,調用 對象.屬性.__doc__ ,此參數是該屬性的描述信息
class Foo: def get_bar(self): return 'wupeiqi' # *必須兩個參數 def set_bar(self, value): return return 'set value' + value def del_bar(self): return 'wupeiqi' BAR = property(get_bar, set_bar, del_bar, 'description...') obj = Foo() obj.BAR # 自動調用第一個參數中定義的方法:get_bar obj.BAR = "alex" # 自動調用第二個參數中定義的方法:set_bar方法,並將「alex」看成參數傳入 del Foo.BAR # 自動調用第三個參數中定義的方法:del_bar方法 obj.BAE.__doc__ # 自動獲取第四個參數中設置的值:description...
因爲靜態字段方式建立屬性具備三種訪問方式,咱們能夠根據他們幾個屬性的訪問特色,分別將三個方法定義爲對同一個屬性:獲取、修改、刪除
1 class Goods(object): 2 3 def __init__(self): 4 # 原價 5 self.original_price = 100 6 # 折扣 7 self.discount = 0.8 8 9 def get_price(self): 10 # 實際價格 = 原價 * 折扣 11 new_price = self.original_price * self.discount 12 return new_price 13 14 def set_price(self, value): 15 self.original_price = value 16 17 def del_price(self, value): 18 del self.original_price 19 20 PRICE = property(get_price, set_price, del_price, '價格屬性描述...') 21 22 obj = Goods() 23 obj.PRICE # 獲取商品價格 24 obj.PRICE = 200 # 修改商品原價 25 del obj.PRICE # 刪除商品原價
注意:Python WEB框架 Django 的視圖中 request.POST 就是使用的靜態字段的方式建立的屬性
1 class WSGIRequest(http.HttpRequest): 2 def __init__(self, environ): 3 script_name = get_script_name(environ) 4 path_info = get_path_info(environ) 5 if not path_info: 6 # Sometimes PATH_INFO exists, but is empty (e.g. accessing 7 # the SCRIPT_NAME URL without a trailing slash). We really need to 8 # operate as if they'd requested '/'. Not amazingly nice to force 9 # the path like this, but should be harmless. 10 path_info = '/' 11 self.environ = environ 12 self.path_info = path_info 13 self.path = '%s/%s' % (script_name.rstrip('/'), path_info.lstrip('/')) 14 self.META = environ 15 self.META['PATH_INFO'] = path_info 16 self.META['SCRIPT_NAME'] = script_name 17 self.method = environ['REQUEST_METHOD'].upper() 18 _, content_params = cgi.parse_header(environ.get('CONTENT_TYPE', '')) 19 if 'charset' in content_params: 20 try: 21 codecs.lookup(content_params['charset']) 22 except LookupError: 23 pass 24 else: 25 self.encoding = content_params['charset'] 26 self._post_parse_error = False 27 try: 28 content_length = int(environ.get('CONTENT_LENGTH')) 29 except (ValueError, TypeError): 30 content_length = 0 31 self._stream = LimitedStream(self.environ['wsgi.input'], content_length) 32 self._read_started = False 33 self.resolver_match = None 34 35 def _get_scheme(self): 36 return self.environ.get('wsgi.url_scheme') 37 38 def _get_request(self): 39 warnings.warn('`request.REQUEST` is deprecated, use `request.GET` or ' 40 '`request.POST` instead.', RemovedInDjango19Warning, 2) 41 if not hasattr(self, '_request'): 42 self._request = datastructures.MergeDict(self.POST, self.GET) 43 return self._request 44 45 @cached_property 46 def GET(self): 47 # The WSGI spec says 'QUERY_STRING' may be absent. 48 raw_query_string = get_bytes_from_wsgi(self.environ, 'QUERY_STRING', '') 49 return http.QueryDict(raw_query_string, encoding=self._encoding) 50 51 # ############### 看這裏看這裏 ############### 52 def _get_post(self): 53 if not hasattr(self, '_post'): 54 self._load_post_and_files() 55 return self._post 56 57 # ############### 看這裏看這裏 ############### 58 def _set_post(self, post): 59 self._post = post 60 61 @cached_property 62 def COOKIES(self): 63 raw_cookie = get_str_from_wsgi(self.environ, 'HTTP_COOKIE', '') 64 return http.parse_cookie(raw_cookie) 65 66 def _get_files(self): 67 if not hasattr(self, '_files'): 68 self._load_post_and_files() 69 return self._files 70 71 # ############### 看這裏看這裏 ############### 72 POST = property(_get_post, _set_post) 73 74 FILES = property(_get_files) 75 REQUEST = property(_get_request)
因此,定義屬性共有兩種方式,分別是【裝飾器】和【靜態字段】,而【裝飾器】方式針對經典類和新式類又有所不一樣。
類的全部成員在上一步驟中已經作了詳細的介紹,對於每個類的成員而言都有兩種形式:
私有成員和公有成員的定義不一樣:私有成員命名時,前兩個字符是下劃線。(特殊成員除外,例如:__init__、__call__、__dict__等)
1 class C: 2 def __init__(self): 3 self.name = '公有字段' 4 self.__foo = "私有字段"
私有成員和公有成員的訪問限制不一樣:
靜態字段
1 class C: 2 3 name = "公有靜態字段" 4 5 def func(self): 6 print C.name 7 8 class D(C): 9 10 def show(self): 11 print C.name 12 13 14 C.name # 類訪問 15 16 obj = C() 17 obj.func() # 類內部能夠訪問 18 19 obj_son = D() 20 obj_son.show() # 派生類中能夠訪問
1 class C: 2 3 __name = "公有靜態字段" 4 5 def func(self): 6 print C.__name 7 8 class D(C): 9 10 def show(self): 11 print C.__name 12 13 14 C.__name # 類訪問 ==> 錯誤 15 16 obj = C() 17 obj.func() # 類內部能夠訪問 ==> 正確 18 19 obj_son = D() 20 obj_son.show() # 派生類中能夠訪問 ==> 錯誤
普通字段
公有普通字段:對象能夠訪問;類內部能夠訪問;派生類中能夠訪問
私有普通字段:僅類內部能夠訪問;
ps:若是想要強制訪問私有字段,能夠經過 【對象._類名__私有字段明 】訪問(如:obj._C__foo),不建議強制訪問私有成員。
1 class C: 2 3 def __init__(self): 4 self.foo = "公有字段" 5 6 def func(self): 7 print self.foo # 類內部訪問 8 9 class D(C): 10 11 def show(self): 12 print self.foo # 派生類中訪問 13 14 obj = C() 15 16 obj.foo # 經過對象訪問 17 obj.func() # 類內部訪問 18 19 obj_son = D(); 20 obj_son.show() # 派生類中訪問
1 class C: 2 3 def __init__(self): 4 self.__foo = "私有字段" 5 6 def func(self): 7 print self.foo # 類內部訪問 8 9 class D(C): 10 11 def show(self): 12 print self.foo # 派生類中訪問 13 14 obj = C() 15 16 obj.__foo # 經過對象訪問 ==> 錯誤 17 obj.func() # 類內部訪問 ==> 正確 18 19 obj_son = D(); 20 obj_son.show() # 派生類中訪問 ==> 錯誤
方法、屬性的訪問於上述方式類似,即:私有成員只能在類內部使用
ps:非要訪問私有屬性的話,能夠經過 對象._類__屬性名
上文介紹了Python的類成員以及成員修飾符,從而瞭解到類中有字段、方法和屬性三大類成員,而且成員名前若是有兩個下劃線,則表示該成員是私有成員,私有成員只能由類內部調用。不管人或事物每每都有不按套路出牌的狀況,Python的類成員也是如此,存在着一些具備特殊含義的成員,詳情以下:
1. __doc__
表示類的描述信息
1 class Foo: 2 """ 描述類信息,這是用於看片的神奇 """ 3 4 def func(self): 5 pass 6 7 print Foo.__doc__ 8 #輸出:類的描述信息
2. __module__ 和 __class__
__module__ 表示當前操做的對象在那個模塊
__class__ 表示當前操做的對象的類是什麼
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 class C: 5 6 def __init__(self): 7 self.name = 'wupeiqi' 8 9 lib/aa.py
1 from lib.aa import C 2 3 obj = C() 4 print obj.__module__ # 輸出 lib.aa,即:輸出模塊 5 print obj.__class__ # 輸出 lib.aa.C,即:輸出類
3. __init__
構造方法,經過類建立對象時,自動觸發執行。
1 class Foo: 2 3 def __init__(self, name): 4 self.name = name 5 self.age = 18 6 7 8 obj = Foo('wupeiqi') # 自動執行類中的 __init__ 方法
4. __del__
析構方法,當對象在內存中被釋放時,自動觸發執行。
注:此方法通常無須定義,由於Python是一門高級語言,程序員在使用時無需關心內存的分配和釋放,由於此工做都是交給Python解釋器來執行,因此,析構函數的調用是由解釋器在進行垃圾回收時自動觸發執行的。
1 class Foo: 2 3 def __del__(self): 4 pass
5. __call__
對象後面加括號,觸發執行。
注:構造方法的執行是由建立對象觸發的,即:對象 = 類名() ;而對於 __call__ 方法的執行是由對象後加括號觸發的,即:對象() 或者 類()()
1 class Foo: 2 3 def __init__(self): 4 pass 5 6 def __call__(self, *args, **kwargs): 7 8 print '__call__' 9 10 11 obj = Foo() # 執行 __init__ 12 obj() # 執行 __call__
6. __dict__
類或對象中的全部成員
上文中咱們知道:類的普通字段屬於對象;類中的靜態字段和方法等屬於類,即:
1 class Province: 2 3 country = 'China' 4 5 def __init__(self, name, count): 6 self.name = name 7 self.count = count 8 9 def func(self, *args, **kwargs): 10 print 'func' 11 12 # 獲取類的成員,即:靜態字段、方法、 13 print Province.__dict__ 14 # 輸出:{'country': 'China', '__module__': '__main__', 'func': <function func at 0x10be30f50>, '__init__': <function __init__ at 0x10be30ed8>, '__doc__': None} 15 16 obj1 = Province('HeBei',10000) 17 print obj1.__dict__ 18 # 獲取 對象obj1 的成員 19 # 輸出:{'count': 10000, 'name': 'HeBei'} 20 21 obj2 = Province('HeNan', 3888) 22 print obj2.__dict__ 23 # 獲取 對象obj1 的成員 24 # 輸出:{'count': 3888, 'name': 'HeNan'}
7. __str__
若是一個類中定義了__str__方法,那麼在打印 對象 時,默認輸出該方法的返回值。
1 class Foo: 2 3 def __str__(self): 4 return 'wupeiqi' 5 6 7 obj = Foo() 8 print obj 9 # 輸出:wupeiqi
八、__getitem__、__setitem__、__delitem__
用於索引操做,如字典。以上分別表示獲取、設置、刪除數據
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 class Foo(object): 4 def __getitem__(self, key): 5 print '__getitem__',key 6 def __setitem__(self, key, value): 7 print '__setitem__',key,value 8 def __delitem__(self, key): 9 print '__delitem__',key 10 obj = Foo() 11 result = obj['k1'] # 自動觸發執行 __getitem__ 12 obj['k2'] = 'wupeiqi' # 自動觸發執行 __setitem__ 13 del obj['k1'] # 自動觸發執行 __delitem__
九、__getslice__、__setslice__、__delslice__
該三個方法用於分片操做,如:列表
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 class Foo(object): 4 def __getslice__(self, i, j): 5 print '__getslice__',i,j 6 def __setslice__(self, i, j, sequence): 7 print '__setslice__',i,j 8 def __delslice__(self, i, j): 9 print '__delslice__',i,j 10 obj = Foo() 11 obj[-1:1] # 自動觸發執行 __getslice__ 12 obj[0:1] = [11,22,33,44] # 自動觸發執行 __setslice__ 13 del obj[0:2] # 自動觸發執行 __delslice__
10. __iter__
用於迭代器,之因此列表、字典、元組能夠進行for循環,是由於類型內部定義了 __iter__
1 class Foo(object): 2 pass 3 4 5 obj = Foo() 6 7 for i in obj: 8 print i 9 10 # 報錯:TypeError: 'Foo' object is not iterable
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 class Foo(object): 5 6 def __iter__(self): 7 pass 8 9 obj = Foo() 10 11 for i in obj: 12 print i 13 14 # 報錯:TypeError: iter() returned non-iterator of type 'NoneType'
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 class Foo(object): 5 6 def __init__(self, sq): 7 self.sq = sq 8 9 def __iter__(self): 10 return iter(self.sq) 11 12 obj = Foo([11,22,33,44]) 13 14 for i in obj: 15 print i
以上步驟能夠看出,for循環迭代的實際上是 iter([11,22,33,44]) ,因此執行流程能夠變動爲:
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 obj = iter([11,22,33,44]) 4 for i in obj: 5 print i
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 obj = iter([11,22,33,44]) 5 6 while True: 7 val = obj.next() 8 print val
11. __new__ 和 __metaclass__
閱讀如下代碼:
1 class Foo(object): 2 def __init__(self): 3 pass 4 obj = Foo() # obj是經過Foo類實例化的對象
上述代碼中,obj 是經過 Foo 類實例化的對象,其實,不只 obj 是一個對象,Foo類自己也是一個對象,由於在Python中一切事物都是對象。
若是按照一切事物都是對象的理論:obj對象是經過執行Foo類的構造方法建立,那麼Foo類對象應該也是經過執行某個類的 構造方法 建立。
1 print type(obj) # 輸出:<class '__main__.Foo'> 表示,obj 對象由Foo類建立 2 print type(Foo) # 輸出:<type 'type'> 表示,Foo類對象由 type 類建立
因此,obj對象是Foo類的一個實例,Foo類對象是 type 類的一個實例,即:Foo類對象 是經過type類的構造方法建立。
那麼,建立類就能夠有兩種方式:
a). 普通方式
1 class Foo(object): 2 3 def func(self): 4 print 'hello wupeiqi'
b).特殊方式(type類的構造函數)
1 def func(self): 2 print 'hello wupeiqi' 3 4 Foo = type('Foo',(object,), {'func': func}) 5 #type第一個參數:類名 6 #type第二個參數:當前類的基類 7 #type第三個參數:類的成員
==》 類 是由 type 類實例化產生
那麼問題來了,類默認是由 type 類實例化產生,type類中如何實現的建立類?類又是如何建立對象?
答:類中有一個屬性 __metaclass__,其用來表示該類由 誰 來實例化建立,因此,咱們能夠爲 __metaclass__ 設置一個type類的派生類,從而查看 類 建立的過程。
1 class MyType(type): 2 3 def __init__(self, what, bases=None, dict=None): 4 super(MyType, self).__init__(what, bases, dict) 5 6 def __call__(self, *args, **kwargs): 7 obj = self.__new__(self, *args, **kwargs) 8 9 self.__init__(obj) 10 11 class Foo(object): 12 13 __metaclass__ = MyType 14 15 def __init__(self, name): 16 self.name = name 17 18 def __new__(cls, *args, **kwargs): 19 return object.__new__(cls, *args, **kwargs) 20 21 # 第一階段:解釋器從上到下執行代碼建立Foo類 22 # 第二階段:經過Foo類建立obj對象 23 obj = Foo()