面相對象程序設計中,類方法和靜態方法是經常用到的兩個術語。
邏輯上講:類方法是只能由類名調用;靜態方法可以由類名或對象名進行調用。
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 非常相似,但在用法上依然有一些明顯的區別。classmethod 必須有一個指向 類對象 的引用作為第一個參數,而 staticmethod 可以沒有任何參數。
讓我們看幾個例子。
例子 – 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).
很明顯,這個類的對象可以存儲日期信息(不包括時區,假設他們都存儲在 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 方法用于初始化對象的屬性,它的第一個參數一定是 self,用于指向已經創建好的對象。
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 可以做一些很棒的東西。
比如我們可以支持從特定格式的日期字符串來創建對象,它的格式是 (‘dd-mm-yyyy')。很明顯,我們只能在其他地方而不是 init 方法里實現這個功能。
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。
使用得到的信息初始化對象
代碼如下
day, month, year = map(int, string_date.split('-'))date1 = Date(day, month, year)
新聞熱點
疑難解答