欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2017年10月27日 16:40:34   作者:駑馬  
這篇文章主要介紹了Python探索之靜態(tài)方法和類(lèi)方法的區(qū)別詳解,小編覺(jué)得還是挺不錯(cuò)的,這里分享給大家,供需要的朋友參考。

面相對(duì)象程序設(shè)計(jì)中,類(lèi)方法和靜態(tài)方法是經(jīng)常用到的兩個(gè)術(shù)語(yǔ)。
邏輯上講:類(lèi)方法是只能由類(lèi)名調(diào)用;靜態(tài)方法可以由類(lèi)名或?qū)ο竺M(jìn)行調(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 必須有一個(gè)指向 類(lèi)對(duì)象 的引用作為第一個(gè)參數(shù),而 staticmethod 可以沒(méi)有任何參數(shù)。

讓我們看幾個(gè)例子。

例子 – 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).

很明顯,這個(gè)類(lèi)的對(duì)象可以存儲(chǔ)日期信息(不包括時(shí)區(qū),假設(shè)他們都存儲(chǔ)在 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 方法用于初始化對(duì)象的屬性,它的第一個(gè)參數(shù)一定是 self,用于指向已經(jīng)創(chuàng)建好的對(duì)象。

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 可以做一些很棒的東西。

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

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。

使用得到的信息初始化對(duì)象

代碼如下

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

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

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++ 可以方便的使用重載來(lái)解決這個(gè)問(wèn)題,但是 python 不具備類(lèi)似的特性。 所以接下來(lái)我們要使用 classmethod 來(lái)幫我們實(shí)現(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.

讓我們?cè)谧屑?xì)的分析下上面的實(shí)現(xiàn),看看它的好處。

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

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 沒(méi)有任何必選參數(shù),而 classmethod 第一個(gè)參數(shù)永遠(yuǎn)是 cls, instancemethod 第一個(gè)參數(shù)永遠(yuǎn)是 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)方法的使用中可以看出,我們不會(huì)訪問(wèn)到 class 本身 – 它基本上只是一個(gè)函數(shù),在語(yǔ)法上就像一個(gè)方法一樣,但是沒(méi)有訪問(wèn)對(duì)象和它的內(nèi)部(字段和其他方法),相反 classmethod 會(huì)訪問(wèn) cls, instancemethod 會(huì)訪問(wèn) self。

總結(jié)

以上就是本文關(guān)于Python探索之靜態(tài)方法和類(lèi)方法的區(qū)別詳解的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站:Python探索之爬取電商售賣(mài)信息代碼示例、Python面向?qū)ο缶幊袒A(chǔ)解析(一)等,如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持。

相關(guān)文章

  • python中定時(shí)器的高級(jí)使用方式詳解

    python中定時(shí)器的高級(jí)使用方式詳解

    在Python編程中,定時(shí)器是一種非常有用的工具,用于執(zhí)行特定任務(wù)或函數(shù),本文將介紹一些高級(jí)的定時(shí)器使用方式,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-02-02
  • Pygame鼠標(biāo)進(jìn)行圖片的移動(dòng)與縮放案例詳解

    Pygame鼠標(biāo)進(jìn)行圖片的移動(dòng)與縮放案例詳解

    pygame是Python的第三方庫(kù),里面提供了使用Python開(kāi)發(fā)游戲的基礎(chǔ)包。本文將介紹如何通過(guò)Pygame實(shí)現(xiàn)鼠標(biāo)進(jìn)行圖片的移動(dòng)與縮放,感興趣的可以關(guān)注一下
    2021-12-12
  • Django中的AutoField字段使用

    Django中的AutoField字段使用

    這篇文章主要介紹了Django中的AutoField字段使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-05-05
  • 如何使用Selenium實(shí)現(xiàn)簡(jiǎn)單的網(wǎng)絡(luò)自動(dòng)化操作指南

    如何使用Selenium實(shí)現(xiàn)簡(jiǎn)單的網(wǎng)絡(luò)自動(dòng)化操作指南

    Selenium是一個(gè)用于Web應(yīng)用測(cè)試的工具,Selenium測(cè)試直接運(yùn)行在瀏覽器中,就像真正的用戶在操作一樣,這篇文章主要給大家介紹了關(guān)于如何使用Selenium實(shí)現(xiàn)簡(jiǎn)單的網(wǎng)絡(luò)自動(dòng)化操作的相關(guān)資料,需要的朋友可以參考下
    2024-03-03
  • Python函數(shù)默認(rèn)參數(shù)設(shè)置的具體方法

    Python函數(shù)默認(rèn)參數(shù)設(shè)置的具體方法

    本文主要介紹了Python函數(shù)默認(rèn)參數(shù)設(shè)置,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • pyqt5讓圖片自適應(yīng)QLabel大小上以及移除已顯示的圖片方法

    pyqt5讓圖片自適應(yīng)QLabel大小上以及移除已顯示的圖片方法

    今天小編就為大家分享一篇pyqt5讓圖片自適應(yīng)QLabel大小上以及移除已顯示的圖片方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-06-06
  • Python中threading模塊的Lock和RLock區(qū)別詳解

    Python中threading模塊的Lock和RLock區(qū)別詳解

    這篇文章主要介紹了Python中threading模塊的Lock和RLock區(qū)別詳解,Lock鎖是Python的原始鎖,在鎖定時(shí)不屬于任何一個(gè)線程,在調(diào)用了 lock.acquire() 方法后,進(jìn)入鎖定狀態(tài),lock.release()方法可以解鎖,底層是通過(guò)一個(gè)函數(shù)來(lái)實(shí)現(xiàn)的,需要的朋友可以參考下
    2023-09-09
  • python機(jī)器學(xué)習(xí)之貝葉斯分類(lèi)

    python機(jī)器學(xué)習(xí)之貝葉斯分類(lèi)

    這篇文章主要為大家詳細(xì)介紹了python機(jī)器學(xué)習(xí)之貝葉斯分類(lèi)的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-03-03
  • python?pyvis庫(kù)創(chuàng)建可視化交互式網(wǎng)絡(luò)圖

    python?pyvis庫(kù)創(chuàng)建可視化交互式網(wǎng)絡(luò)圖

    這篇文章主要為大家介紹了python?pyvis庫(kù)創(chuàng)建可視化交互式網(wǎng)絡(luò)圖,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2024-01-01
  • 關(guān)于Python Error標(biāo)準(zhǔn)異常的總結(jié)

    關(guān)于Python Error標(biāo)準(zhǔn)異常的總結(jié)

    這篇文章主要介紹了關(guān)于Python Error標(biāo)準(zhǔn)異常的總結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-09-09

最新評(píng)論