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中optionParser模块的使用方法实例教程
Aug 29 Python
python多线程用法实例详解
Jan 15 Python
python获取android设备的GPS信息脚本分享
Mar 06 Python
提升Python程序运行效率的6个方法
Mar 31 Python
微信跳一跳小游戏python脚本
Jan 05 Python
Python处理文本换行符实例代码
Feb 03 Python
WxPython建立批量录入框窗口
Feb 27 Python
opencv python 图像轮廓/检测轮廓/绘制轮廓的方法
Jul 03 Python
python字典setdefault方法和get方法使用实例
Dec 25 Python
Python基础教程之输入输出和运算符
Jul 26 Python
Python如何读取、写入CSV数据
Jul 28 Python
Python 多线程C段扫描、检测 Ping扫描脚本的实现
Sep 03 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
虫族 Zerg 热键控制
2020/03/14 星际争霸
《PHP边学边教》(01.开篇――准备工作)
2006/12/13 PHP
PHP实现批量修改文件后缀名的方法
2015/07/30 PHP
Laravel 模型关联基础教程详解
2019/09/17 PHP
关于IFRAME 自适应高度的研究
2006/07/20 Javascript
JavaScript 私有成员分析
2009/01/13 Javascript
招聘网站基于jQuery实现自动刷新简历
2015/05/10 Javascript
javascript将DOM节点添加到文档的方法实例分析
2015/08/04 Javascript
实例讲解JavaScript中instanceof运算符的用法
2016/06/08 Javascript
深入理解node.js之path模块
2017/05/03 Javascript
jQuery DOM节点的遍历方法小结
2017/08/15 jQuery
jQuery实现IE输入框完成placeholder标签功能的方法
2017/09/20 jQuery
JS实现DOM删除节点操作示例
2018/04/04 Javascript
jQuery实现的点击图片居中放大缩小功能示例
2019/01/16 jQuery
每天学点Vue源码之vm.$mount挂载函数
2019/03/11 Javascript
vue点击按钮动态创建与删除组件功能
2019/12/29 Javascript
Vue生命周期activated之返回上一页不重新请求数据操作
2020/07/26 Javascript
[45:14]Optic vs VP 2018国际邀请赛淘汰赛BO3 第二场 8.24
2018/08/25 DOTA
pygame学习笔记(1):矩形、圆型画图实例
2015/04/15 Python
Python引用模块和查找模块路径
2016/03/17 Python
Python利用operator模块实现对象的多级排序详解
2017/05/09 Python
python pandas 如何替换某列的一个值
2018/06/09 Python
python使用scrapy发送post请求的坑
2018/09/04 Python
如何使用python爬虫爬取要登陆的网站
2019/07/12 Python
python批量修改ssh密码的实现
2019/08/08 Python
Pycharm创建项目时如何自动添加头部信息
2019/11/14 Python
使用python实现数组、链表、队列、栈的方法
2019/12/20 Python
Python实现遗传算法(二进制编码)求函数最优值方式
2020/02/11 Python
浅析与CSS3的loading动画加载相关的transition优化
2015/05/18 HTML / CSS
Paradox London官方网站:英国新娘鞋婚礼鞋品牌
2019/08/29 全球购物
优秀应届生推荐信
2013/11/09 职场文书
入团者的自我评价分享
2013/12/02 职场文书
商场中秋节广播稿
2014/01/17 职场文书
小学少先队工作总结2015
2015/05/26 职场文书
2016领导干部廉洁自律心得体会
2016/01/13 职场文书
《鲁滨逊漂流记》之六读后感(4篇)
2019/09/29 职场文书