Python 中classmethod和staticmethod區別
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.
Boilerplate
Let's assume an example of a class, dealing with date information (this is what will be our boilerplate to cook on):
classDate(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).
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.
Class Method
We have some tasks that can be nicely done using classmethod
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.
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:
day, month, year = map(int, string_date.split('-'))
date1 =Date(day, month, year)
For this purpose, C++ has such feature as overloading, but Python lacks that feature- so here's when classmethod
applies.
Lets create another "constructor".
@classmethoddef 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 ourDate
class, all children will havefrom_string
defined also.
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:
@staticmethoddef is_date_valid(date_as_string):
day, month, year = map(int, date_as_string.split('-'))return day <=31and month <=12and 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.
相關推薦
Python 中classmethod和staticmethod區別
Though classmethod and staticmethod are quite similar, there's a slight difference in usage for both entities: classmethod must have a reference to a c
python @classmethod 和 @staticmethod區別,以及類中方法引數cls和self的區別
staticmethod 首先來看@staticmethod,這個裝飾器很好理解,就是讓類中的方法變成一個普通的函式(因為是普通函式,並沒有繫結在任何一個特定的類或者例項上。所以與不需要物件例項化就可以直接呼叫)。可以使用類或者類的例項呼叫,並且沒有任何隱含引數的傳入,
classmethod和staticmethod區別(轉載)
轉載 eth -a lan targe tween 內部 pytho -s 主要classmethod是被類直接調用使用 statifcmethod是在類內部訪問時候並且是能被類直接調用時候使用 原文鏈接地址:click classmethod和staticmethod區
Python中__repr__和__str__區別
close 提示 bsp pri urn 創建 pla 不同 並不是 1.先看區別 1 class Test(object): 2 def __init__(self, value=‘hello, world!‘): 3 self.data
Python中is和==的區別
int 要素 com 分別是 htm python get 參考資料 元組類型 Python中有很多運算符,今天我們就來講講is和==兩種運算符在應用上的本質區別是什麽。 在講is和==這兩種運算符區別之前,首先要知道Python中對象包含的三個基本要素,分別是:id(身份
classmethod和staticmethod區別
sel ati sta 習慣 pri span () 類方法 定義 實例方法:在類中,定義的方法,這個方法的第一個參數默認是實例對象,一般習慣使用self 類方法:在類中,定義的方法,這個方法的第一個參數默認是類對象,一般習慣用cls表示,用@cla
python的@classmethod和@staticmethod
不能 函數 靜態類 rep str 法則 cor 字段 日期格 本文是對StackOverflow上的一篇高贊回答的不完全翻譯,原文鏈接:meaning-of-classmethod-and-staticmethod-for-beginner Python面向對象編程中,類
Python中is和==的區別(面試題)
面試的時候,當問到 is 和 == 的區別時,有很多同學對這個問題不是很清楚,有的人理解但是表述不清楚,接下來我們通過本文對這個做一個深刻的理解。 我們來看一個例子: 我們可以從上面看出,有的is和==相同,而有的不同呢?我們先看看官方文件裡面怎麼解釋這兩者之間的區別: 官方文件中說 is
Python中break和continue區別
break跳出整個迴圈,而continue跳出本次迴圈 continue語句用來告訴python跳過當前迴圈,進行下一個迴圈 break語句用來終止迴圈語句,即迴圈條件沒有False條件或者序列還沒被完全遞迴完,也會停止執行迴圈語句。 break和continue語
Python 中 For 和 While 區別
1.for迴圈是遍歷列表和元組,而while迴圈只要迴圈不滿足,則會結束迴圈 #for..in迴圈,遍歷列表和元組 list1 = [1,2,3,4,5] for i in list1: print(i) tuple1 = (1,2,3,4,5) for m in tuple1
python中 is 和 == 的區別
Python中的物件包含三要素:id、type、value 其中:id用來唯一標識一個物件,type標識物件的型別,value是物件的值 is判斷的是a物件是否就是b物件,是通過id來判斷的 ==判斷的是a物件的值是否和b物件的值相等,是通過value來判斷的 https:/
python基礎(8)python中is和==的區別詳解
# 前置知識點 當我們建立一個物件時,我們要知道它內部幹了些什麼 - 1.建立了一個隨機id,開闢了一片記憶體地址 - 2.自動聲明瞭這個物件的型別type - 3.給這個物件賦值value ## 小例子 ``` a = 1 print(id(1)) print(id(a)) print(ty
Python中的例項方法、classmethod和staticmethod的區別
class NewsPaper(object): # 類屬性 __print_times = 0 # 下劃線表示私有屬性 # 例項方法 def __init__(self, title, content): self.t
python中靜態方法(@staticmethod)和類方法(@classmethod)的區別
方法 屬性方法 參數 pre 如果 icm ssm 使用 類方法 一般來說,要使用某個類的方法,需要先實例化一個對象再調用方法。 而使用@staticmethod或@classmethod,就可以不需要實例化,直接類名.方法名()來調用。 這有利於組織代碼,把某些應該屬於某
Python中@property和@classmethod和@staticmethod
return 被調用 命令 成了 aps display init 命名空間 類的方法 前戲 首先,先要弄清楚一個類裏面的,各個組成部分都應該怎麽稱呼。 - 註:可能叫法會不太一樣。 關於@property 顧名思義:它的意思為‘屬性’。
Python 中的 classmethod 和 staticmethod
original Go got typeerror print ini 靜態 main method 類中最常用的方法是實例方法, 即通過通過實例作為第一個參數的方法。 舉個例子,一個基本的實例方法就向下面這個: class Kls(object): def
python中@classmethod @staticmethod區別
python bject 函數 需要 @class 輸出結果 icm nbsp static python staticmethod 返回函數的靜態方法。 該方法不強制要求傳遞參數,如下聲明一個靜態方法: class C(object): @staticm
Python中sort()和sorted()的區別
-s 可變對象 傳遞 內置函數 ict pan 16px nbsp lin 1、sort()是可變對象(字典)的方法,無參數,無返回值, sort()會改變可變對象,因此無需返回值。例如: list: 1 >>> a = [4,3,7,8] 2 >
python中return和print的區別
bsp 不同 urn text 一是 什麽 cnblogs style c99 之前遇到這個問題,就試著對比幾種不同的結果,總結啦一下return和print的區別。 總結: return的作用之一是返回計算的值print的作用是輸出數據到控制端在第一個結果中什麽都沒
Python 中 Iterator和Iterable的區別
pytho 數據 執行 next 判斷 -h 實現 col http (轉載:http://blog.csdn.net/passionkk/article/details/49929887) Python中 list,truple,str,dict這些都可以被叠代,但他們並