成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

【譯】python 靜態(tài)方法和類方法的區(qū)別

Crazy_Coder / 2165人閱讀

摘要:盡管和非常相似,但在用法上依然有一些明顯的區(qū)別。所以,從靜態(tài)方法的使用中可以看出,我們不會訪問到本身它基本上只是一個函數(shù),在語法上就像一個方法一樣,但是沒有訪問對象和它的內(nèi)部字段和其他方法,相反會訪問,會訪問。

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 方法里實(shí)現(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 來幫我們實(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.

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

我們在一個方法中實(shí)現(xiàn)了功能,因此它是可重用的。 這里的封裝處理的不錯(如果你發(fā)現(xiàn)還可以在代碼的任意地方添加一個不屬于 Date 的函數(shù)來實(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ù)永遠(yuǎn)是 cls, instancemethod 第一個參數(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)方法的使用中可以看出,我們不會訪問到 class 本身 - 它基本上只是一個函數(shù),在語法上就像一個方法一樣,但是沒有訪問對象和它的內(nèi)部(字段和其他方法),相反 classmethod 會訪問 cls, instancemethod 會訪問 self。

參考

Meaning of @classmethod and @staticmethod for beginner?

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/40935.html

相關(guān)文章

  • 】函數(shù)組件和類組件有什么不同?

    摘要:但是,你可能已經(jīng)注意到,當(dāng)你試圖通過指定依賴數(shù)組來優(yōu)化時,可能會遇到帶有過時閉包的錯誤。這是否意味著閉包是問題所在我不這么認(rèn)為。到目前為止,我所看到的所有情況下,過時的閉包問題都是由于錯誤地假設(shè)函數(shù)不更改或總是相同而發(fā)生的。 原文鏈接:https://overreacted.io/how-ar... 在很長一段時間內(nèi),標(biāo)準(zhǔn)答案是class components提供更多的特性(像sta...

    gself 評論0 收藏0
  • Python方法靜態(tài)方法之間區(qū)別

      小編寫這篇文章的主要目的,是講述一下關(guān)于Python的一些小技巧,包括類方法與靜態(tài)方法之間,存在一些什么區(qū)別呢?怎么從真正的意義上去理解關(guān)于其不同之間的區(qū)別呢?下面就給大家詳細(xì)的解答下。  前言  在python的類中不僅可以有methods,還可以有變量,這些變量稱為類屬性,例如如下代碼中Book類的TYPES即為類屬性?! ☆愔械姆椒ǚ譃?類:  1.實(shí)例方法instance method...

    89542767 評論0 收藏0
  • python函數(shù)和類一些研究

    摘要:與通常認(rèn)為實(shí)例方法是的,而類方法是的,這種說法也沒錯,只是對于不同類型變量來說,結(jié)果是不同的測試一下結(jié)果顯示的都是直接從類訪問,結(jié)果這個實(shí)例方法顯示的是??梢灾赖囊饬x并不是始終不變的,對于不同的對象來說意義并不一樣。 bound與unbound 通常認(rèn)為實(shí)例方法是bound的,而類方法是unbound的,這種說法也沒錯,只是對于不同類型變量來說,結(jié)果是不同的 class A(obje...

    Wildcard 評論0 收藏0
  • []Java和Python——應(yīng)該先學(xué)習(xí)哪種編程語言

    摘要:和是目前兩種非常流行且功能強(qiáng)大的編程語言。初級程序員常常感到困惑,最常被問到的問題就是應(yīng)該學(xué)習(xí)還是,是不是容易上手,應(yīng)該推薦給初學(xué)者學(xué)習(xí)什么樣的編程語言等等。在學(xué)習(xí)任何編程語言之前,你必須知道它們之間的區(qū)別。 Java和Python是目前兩種非常流行且功能強(qiáng)大的編程語言。初級程序員常常感到困惑,最常被問到的問題就是應(yīng)該學(xué)習(xí)Java還是Python,Python是不是容易上手,應(yīng)該推薦給...

    honmaple 評論0 收藏0
  • [] 屬性訪問、特性和描述符 1

    摘要:許多程序員發(fā)現(xiàn)賦值語句比方法函數(shù)看起來更清晰。自從和屬性的創(chuàng)建來自,我們必須經(jīng)常定義特性使用如下代碼這允許我們用一條簡單的語句添加一張牌到手中像下面這樣前面的賦值語句有一個缺點(diǎn),因?yàn)樗雌饋硐褚粡埮铺娲怂械呐啤? 注:原書作者 Steven F. Lott,原書名為 Mastering Object-oriented Python 對象就是一些特性的集合,包括方法和屬性。object...

    褰辯話 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<