Python探索之静态方法和类方法的区别详解


Posted in Python onOctober 27, 2017

面相对象程序设计中,类方法和静态方法是经常用到的两个术语。
逻辑上讲:类方法是只能由类名调用;静态方法可以由类名或对象名进行调用。

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)

理想的情况是 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 来帮我们实现。

@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.

让我们在仔细的分析下上面的实现,看看它的好处。

我们在一个方法中实现了功能,因此它是可重用的。 这里的封装处理的不错(如果你发现还可以在代码的任意地方添加一个不属于 Date 的函数来实现类似的功能,那很显然上面的办法更符合 OOP 规范)。 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 没有任何必选参数,而 classmethod 第一个参数永远是 cls, instancemethod 第一个参数永远是 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.

所以,从静态方法的使用中可以看出,我们不会访问到 class 本身 ? 它基本上只是一个函数,在语法上就像一个方法一样,但是没有访问对象和它的内部(字段和其他方法),相反 classmethod 会访问 cls, instancemethod 会访问 self。

总结

以上就是本文关于Python探索之静态方法和类方法的区别详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:Python探索之爬取电商售卖信息代码示例、Python面向对象编程基础解析(一)等,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持。

Python 相关文章推荐
Python实现在Linux系统下更改当前进程运行用户
Feb 04 Python
Python对list列表结构中的值进行去重的方法总结
May 07 Python
深入学习Python中的装饰器使用
Jun 20 Python
Python操作Excel之xlsx文件
Mar 24 Python
Python实现输出程序执行进度百分比的方法
Sep 16 Python
python字典值排序并取出前n个key值的方法
Oct 17 Python
python字符串切割:str.split()与re.split()的对比分析
Jul 16 Python
linux环境下安装python虚拟环境及注意事项
Jan 07 Python
Python pyautogui模块实现鼠标键盘自动化方法详解
Feb 17 Python
Python json转字典字符方法实例解析
Apr 13 Python
Python如何快速找到多个字典中的公共键(key)
Apr 29 Python
Python 第三方库 openpyxl 的安装过程
Dec 24 Python
Python探索之爬取电商售卖信息代码示例
Oct 27 #Python
Python 列表理解及使用方法
Oct 27 #Python
Python算法之求n个节点不同二叉树个数
Oct 27 #Python
Python探索之自定义实现线程池
Oct 27 #Python
python音频处理用到的操作的示例代码
Oct 27 #Python
彻底理解Python list切片原理
Oct 27 #Python
Python在不同目录下导入模块的实现方法
Oct 27 #Python
You might like
PHP中使用array函数新建一个数组
2015/11/19 PHP
深入理解PHP JSON数组与对象
2016/07/19 PHP
PHP 类与构造函数解析
2017/02/06 PHP
PHP基于GD2函数库实现验证码功能示例
2019/01/27 PHP
调试php程序的简单步骤
2019/10/04 PHP
实现连缀调用的map方法(prototype)
2009/08/05 Javascript
Mootools 1.2教程 滚动条(Slider)
2009/09/15 Javascript
11款新鲜的jQuery插件[附所有demo下载]
2011/01/24 Javascript
js模拟select下拉菜单控件的代码
2013/05/08 Javascript
JavaScript实现简单的二级导航菜单实例
2015/04/15 Javascript
JS实现的通用表单验证插件完整实例
2015/08/20 Javascript
JS查找字符串中出现次数最多的字符
2016/09/05 Javascript
AnjularJS中$scope和$rootScope的区别小结
2016/09/18 Javascript
jQuery内容筛选选择器实例代码
2017/02/06 Javascript
js,jq,css多方面实现简易下拉菜单功能
2017/05/13 Javascript
vue2实现可复用的轮播图carousel组件详解
2017/11/27 Javascript
Javascript 实现 Excel 导入生成图表功能
2018/10/22 Javascript
原生JS 实现的input输入时表格过滤操作示例
2019/08/03 Javascript
如何搜索查找并解决Django相关的问题
2014/06/30 Python
Python记录详细调用堆栈日志的方法
2015/05/05 Python
Python多进程编程multiprocessing代码实例
2020/03/12 Python
Python爬虫实现百度翻译功能过程详解
2020/05/29 Python
用CSS3的box-reflect设置文字倒影效果的方法讲解
2016/03/07 HTML / CSS
英国知名化妆品网站:Revolution Beauty(原TAM Beauty)
2018/02/28 全球购物
美国领先的个性化礼品商城:Personalization Mall
2019/07/27 全球购物
C#中有没有静态构造函数,如果有是做什么用的?
2016/06/04 面试题
Java基础类库面试题
2013/09/04 面试题
考试作弊被抓检讨书
2014/01/10 职场文书
缓刑人员的思想汇报
2014/01/11 职场文书
红领巾心向党演讲稿
2014/09/10 职场文书
卫校毕业生自我鉴定
2014/09/28 职场文书
官僚主义现象查摆问题整改措施
2014/10/04 职场文书
升职自我推荐信范文
2015/03/25 职场文书
浅谈resultMap的用法及关联结果集映射
2021/06/30 Java/Android
详解CSS3.0(Cascading Style Sheet) 层叠级联样式表
2021/07/16 HTML / CSS
TV动画「神渣☆爱豆」公开第一弹主视觉图
2022/03/21 日漫