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

熱線電話:13121318867

登錄
首頁精彩閱讀Python探索之靜態(tài)方法和類方法的區(qū)別詳解
Python探索之靜態(tài)方法和類方法的區(qū)別詳解
2017-11-16
收藏

Python探索之靜態(tài)方法和類方法的區(qū)別詳解

這篇文章主要介紹了Python探索之靜態(tài)方法和類方法的區(qū)別詳解,小編覺得還是挺不錯的,這里分享給大家.

面相對象程序設(shè)計中,類方法和靜態(tài)方法是經(jīng)常用到的兩個術(shù)語。
邏輯上講:類方法是只能由類名調(diào)用;靜態(tài)方法可以由類名或?qū)ο竺M行調(diào)用。
python staticmethod and classmethod    
Though classmethod and staticmethod are quite similar, there's a slight difference in usage for both entities: classmethod must have a reference to a class object as the first parameter, whereas staticmethod can have no parameters at all.
Let's look at all that was said in real examples.

盡管 classmethod 和 staticmethod 非常相似,但在用法上依然有一些明顯的區(qū)別。classmethod 必須有一個指向 類對象 的引用作為第一個參數(shù),而 staticmethod 可以沒有任何參數(shù)。

讓我們看幾個例子。

例子 – Boilerplate

Let's assume an example of a class, dealing with date information (this is what will be our boilerplate to cook on):    
class Date(object):
 
  def __init__(self, day=0, month=0, year=0):
    self.day = day
    self.month = month
    self.year = year

This class obviously could be used to store information about certain dates (without timezone information; let's assume all dates are presented in UTC).

很明顯,這個類的對象可以存儲日期信息(不包括時區(qū),假設(shè)他們都存儲在 UTC)。

Here we have __init__, a typical initializer of Python class instances, which receives arguments as a typical instancemethod, having the first non-optional argument (self) that holds reference to a newly created instance.

這里的 init 方法用于初始化對象的屬性,它的第一個參數(shù)一定是 self,用于指向已經(jīng)創(chuàng)建好的對象。

Class Method

We have some tasks that can be nicely done using classmethods.
Let's assume that we want to create a lot of Date class instances having date information coming from outer source encoded as a string of next format (‘dd-mm-yyyy'). We have to do that in different places of our source code in project.

利用 classmethod 可以做一些很棒的東西。

比如我們可以支持從特定格式的日期字符串來創(chuàng)建對象,它的格式是 (‘dd-mm-yyyy')。很明顯,我們只能在其他地方而不是 init 方法里實現(xiàn)這個功能。

So what we must do here is:
Parse a string to receive day, month and year as three integer variables or a 3-item tuple consisting of that variable.
Instantiate Date by passing those values to initialization call.
This will look like:

大概步驟:

解析字符串,得到整數(shù) day, month, year。

使用得到的信息初始化對象

代碼如下    
day, month, year = map(int, string_date.split('-'))
date1 = Date(day, month, year)

理想的情況是 Date 類本身可以具備處理字符串時間的能力,解決了重用性問題,比如添加一個額外的方法。

For this purpose, C++ has such feature as overloading, but Python lacks that feature- so here's when classmethod applies. Lets create another “constructor”.

C++ 可以方便的使用重載來解決這個問題,但是 python 不具備類似的特性。 所以接下來我們要使用 classmethod 來幫我們實現(xiàn)。
    
@classmethod
 def from_string(cls, date_as_string):
 day, month, year = map(int, date_as_string.split('-'))
 date1 = cls(day, month, year)
 return date1
date2 = Date.from_string('11-09-2012')

Let's look more carefully at the above implementation, and review what advantages we have here:
We've implemented date string parsing in one place and it's reusable now.
Encapsulation works fine here (if you think that you could implement string parsing as a single function elsewhere, this solution fits OOP paradigm far better).
cls is an object that holds class itself, not an instance of the class. It's pretty cool because if we inherit our Date class, all children will have from_string defined also.

讓我們在仔細的分析下上面的實現(xiàn),看看它的好處。

我們在一個方法中實現(xiàn)了功能,因此它是可重用的。 這里的封裝處理的不錯(如果你發(fā)現(xiàn)還可以在代碼的任意地方添加一個不屬于 Date 的函數(shù)來實現(xiàn)類似的功能,那很顯然上面的辦法更符合 OOP 規(guī)范)。 cls 是一個保存了 class 的對象(所有的一切都是對象)。 更妙的是, Date 類的衍生類都會具有 from_string 這個有用的方法。

Static method
What about staticmethod? It's pretty similar to classmethod but doesn't take any obligatory parameters (like a class method or instance method does).
Let's look at the next use case.
We have a date string that we want to validate somehow. This task is also logically bound to Date class we've used so far, but still doesn't require instantiation of it.
Here is where staticmethod can be useful. Let's look at the next piece of code:

staticmethod 沒有任何必選參數(shù),而 classmethod 第一個參數(shù)永遠是 cls, instancemethod 第一個參數(shù)永遠是 self。    
@staticmethod
def is_date_valid(date_as_string):
 day, month, year = map(int, date_as_string.split('-'))
 return day <= 31 and month <= 12 and year <= 3999
 
# usage:
is_date = Date.is_date_valid('11-09-2012')

So, as we can see from usage of staticmethod, we don't have any access to what the class is- it's basically just a function, called syntactically like a method, but without access to the object and it's internals (fields and another methods), while classmethod does.
所以,從靜態(tài)方法的使用中可以看出,我們不會訪問到 class 本身 – 它基本上只是一個函數(shù),在語法上就像一個方法一樣,但是沒有訪問對象和它的內(nèi)部(字段和其他方法),相反 classmethod 會訪問 cls, instancemethod 會訪問 self。
總結(jié)
以上就是本文關(guān)于Python探索之靜態(tài)方法和類方法的區(qū)別詳解的全部內(nèi)容,希望對大家有所幫助。


數(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); }