99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀Python中的對象,方法,類,實例,函數(shù)用法分析
Python中的對象,方法,類,實例,函數(shù)用法分析
2018-01-03
收藏

Python中的對象,方法,類,實例,函數(shù)用法分析

本文實例分析了Python中的對象,方法,類,實例,函數(shù)用法。分享給大家供大家參考。具體分析如下:

Python是一個完全面向?qū)ο蟮恼Z言。不僅實例是對象,類,函數(shù),方法也都是對象。

代碼如下:
class Foo(object):
    static_attr = True
    def method(self):
        pass
foo = Foo()

這段代碼實際上創(chuàng)造了兩個對象,F(xiàn)oo和foo。而Foo同時又是一個類,foo是這個類的實例。
在C++里類型定義是在編譯時完成的,被儲存在靜態(tài)內(nèi)存里,不能輕易修改。在Python里類型本身是對象,和實例對象一樣儲存在堆中,對于解釋器來說類對象和實例對象沒有根本上的區(qū)別。
在Python中每一個對象都有自己的命名空間??臻g內(nèi)的變量被存儲在對象的__dict__里。這樣,F(xiàn)oo類有一個__dict__, foo實例也有一個__dict__,但這是兩個不同的命名空間。
所謂“定義一個類”,實際上就是先生成一個類對象,然后執(zhí)行一段代碼,但把執(zhí)行這段代碼時的本地命名空間設(shè)置成類的__dict__. 所以你可以寫這樣的代碼:

代碼如下:
>>> class Foo(object):
...     bar = 1 + 1
...     qux = bar + 1
...     print "bar: ", bar
...     print "qux: ", qux
...     print locals()
...
bar:  2
qux:  3
{'qux': 3, '__module__': '__main__', 'bar': 2}
>>> print Foo.bar, Foo.__dict__['bar']
2 2
>>> print Foo.qux, Foo.__dict__['qux']
3 3

所謂“定義一個函數(shù)”,實際上也就是生成一個函數(shù)對象。而“定義一個方法”就是生成一
個函數(shù)對象,并把這個對象放在一個類的__dict__中。下面兩種定義方法的形式是等價的:

代碼如下:
>>> class Foo(object):
...     def bar(self):
...         return 2
...
>>> def qux(self):
...     return 3
...
>>> Foo.qux = qux
>>> print Foo.bar, Foo.__dict__['bar']

>>> print Foo.qux, Foo.__dict__['qux']

>>> foo = Foo()
>>> foo.bar()
2
>>> foo.qux()
3

而類繼承就是簡單地定義兩個類對象,各自有不同的__dict__:

代碼如下:
>>> class Cheese(object):
...     smell = 'good'
...     taste = 'good'
...
>>> class Stilton(Cheese):
...     smell = 'bad'
...
>>> print Cheese.smell
good
>>> print Cheese.taste
good
>>> print Stilton.smell
bad
>>> print Stilton.taste
good
>>> print 'taste' in Cheese.__dict__
True
>>> print 'taste' in Stilton.__dict__
False

復(fù)雜的地方在`.`這個運算符上。對于類來說,Stilton.taste的意思是“在Stilton.__dict__中找'taste'. 如果沒找到,到父類Cheese的__dict__里去找,然后到父類的父類,等等。如果一直到object仍沒找到,那么扔一個AttributeError.”
實例同樣有自己的__dict__:

代碼如下:
>>> class Cheese(object):
...     smell = 'good'
...     taste = 'good'
...     def __init__(self, weight):
...         self.weight = weight
...     def get_weight(self):
...         return self.weight
...
>>> class Stilton(Cheese):
...     smell = 'bad'
...
>>> stilton = Stilton('100g')
>>> print 'weight' in Cheese.__dict__
False
>>> print 'weight' in Stilton.__dict__
False
>>> print 'weight' in stilton.__dict__
True

不管__init__()是在哪兒定義的, stilton.__dict__與類的__dict__都無關(guān)。
Cheese.weight和Stilton.weight都會出錯,因為這兩個都碰不到實例的命名空間。而
stilton.weight的查找順序是stilton.__dict__ => Stilton.__dict__ =>
Cheese.__dict__ => object.__dict__. 這與Stilton.taste的查找順序非常相似,僅僅是
在最前面多出了一步。

方法稍微復(fù)雜些。

代碼如下:
>>> print Cheese.__dict__['get_weight']

>>> print Cheese.get_weight

>>> print stilton.get_weight
<__main__.Stilton object at 0x7ff820669190>>
我們可以看到點運算符把function變成了unbound method. 直接調(diào)用類命名空間的函數(shù)和點
運算返回的未綁定方法會得到不同的錯誤:

代碼如下:
>>> Cheese.__dict__['get_weight']()
Traceback (most recent call last):
  File "", line 1, in
TypeError: get_weight() takes exactly 1 argument (0 given)
>>> Cheese.get_weight()
Traceback (most recent call last):
  File "", line 1, in
TypeError: unbound method get_weight() must be called with Cheese instance as
first argument (got nothing instead)

但這兩個錯誤說的是一回事,實例方法需要一個實例。所謂“綁定方法”就是簡單地在調(diào)用方法時把一個實例對象作為第一個參數(shù)。下面這些調(diào)用方法是等價的:

代碼如下:
>>> Cheese.__dict__['get_weight'](stilton)
'100g'
>>> Cheese.get_weight(stilton)
'100g'
>>> Stilton.get_weight(stilton)
'100g'
>>> stilton.get_weight()
'100g'

最后一種也就是平常用的調(diào)用方式,stilton.get_weight(),是點運算符的另一種功能,將stilton.get_weight()翻譯成stilton.get_weight(stilton).
這樣,方法調(diào)用實際上有兩個步驟。首先用屬性查找的規(guī)則找到get_weight, 然后將這個屬性作為函數(shù)調(diào)用,并把實例對象作為第一參數(shù)。這兩個步驟間沒有聯(lián)系。比如說你可以這樣試:

代碼如下:
>>> stilton.weight()
Traceback (most recent call last):
  File "", line 1, in
TypeError: 'str' object is not callable


先查找weight這個屬性,然后將weight做為函數(shù)調(diào)用。但weight是字符串,所以出錯。要注意在這里屬性查找是從實例開始的:

代碼如下:
>>> stilton.get_weight = lambda : '200g'
>>> stilton.get_weight()
'200g'


但是

代碼如下:
>>> Stilton.get_weight(stilton)
'100g'


Stilton.get_weight的查找跳過了實例對象stilton,所以查找到的是沒有被覆蓋的,在Cheese中定義的方法。

getattr(stilton, 'weight')和stilton.weight是等價的。類對象和實例對象沒有本質(zhì)區(qū)別,getattr(Cheese, 'smell')和Cheese.smell同樣是等價的。getattr()與點運算符相比,好處是屬性名用字符串指定,可以在運行時改變。

__getattribute__()是最底層的代碼。如果你不重新定義這個方法,object.__getattribute__()和type.__getattribute__()就是getattr()的具體實現(xiàn),前者用于實例,后者用以類。換句話說,stilton.weight就是object.__getattribute__(stilton, 'weight'). 覆蓋這個方法是很容易出錯的。比如說點運算符會導(dǎo)致無限遞歸:

代碼如下:
def __getattribute__(self, name):
        return self.__dict__[name]__getattribute__()中還有其它的細節(jié),比如說descriptor protocol的實現(xiàn),如果重寫很容易搞錯。

__getattr__()是在__dict__查找沒找到的情況下調(diào)用的方法。一般來說動態(tài)生成屬性要用這個,因為__getattr__()不會干涉到其它地方定義的放到__dict__里的屬性。

代碼如下:
>>> class Cheese(object):
...     smell = 'good'
...     taste = 'good'
...
>>> class Stilton(Cheese):
...     smell = 'bad'
...     def __getattr__(self, name):
...         return 'Dynamically created attribute "%s"' % name
...
>>> stilton = Stilton()
>>> print stilton.taste
good
>>> print stilton.weight
Dynamically created attribute "weight"
>>> print 'weight' in stilton.__dict__
False

由于方法只不過是可以作為函數(shù)調(diào)用的屬性,__getattr__()也可以用來動態(tài)生成方法,但同樣要注意無限遞歸:

代碼如下:
>>> class Cheese(object):
...     smell = 'good'
...     taste = 'good'
...     def __init__(self, weight):
...         self.weight = weight
...
>>> class Stilton(Cheese):
...     smell = 'bad'
...     def __getattr__(self, name):
...         if name.startswith('get_'):
...             def func():
...                 return getattr(self, name[4:])
...             return func
...         else:
...             if hasattr(self, name):
...                 return getattr(self, name)
...             else:
...                 raise AttributeError(name)
...
>>> stilton = Stilton('100g')
>>> print stilton.weight
100g
>>> print stilton.get_weight

>>> print stilton.get_weight()
100g
>>> print stilton.age
Traceback (most recent call last):
  File "", line 1, in
  File "", line 12, in __getattr__
AttributeError: age

希望本文所述對大家的Python程序設(shè)計有所幫助。


數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }