国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python探索之靜態方法和類方法的區別詳解

2020-02-16 10:30:36
字體:
來源:轉載
供稿:網友

面相對象程序設計中,類方法和靜態方法是經常用到的兩個術語。
邏輯上講:類方法是只能由類名調用;靜態方法可以由類名或對象名進行調用。

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)            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 盐池县| 锡林郭勒盟| 娄底市| 浠水县| 龙海市| 平顺县| 辽中县| 习水县| 卢氏县| 乌兰浩特市| 延长县| 彰武县| 上高县| 万宁市| 太保市| 富顺县| 略阳县| 石棉县| 榆林市| 太湖县| 阜宁县| 竹北市| 平果县| 克什克腾旗| 台前县| 宁陵县| 赞皇县| 海南省| 新巴尔虎左旗| 佛教| 万载县| 内乡县| 枝江市| 日喀则市| 邯郸市| 景洪市| 盐亭县| 固镇县| 高唐县| 拉孜县| 英超|