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实现二分查找与bisect模块详解
Jan 13 Python
python实现下载整个ftp目录的方法
Jan 17 Python
浅谈五大Python Web框架
Mar 20 Python
详解python中executemany和序列的使用方法
Aug 12 Python
基于Python代码编辑器的选用(详解)
Sep 13 Python
Python向Excel中插入图片的简单实现方法
Apr 24 Python
Python爬虫实现抓取京东店铺信息及下载图片功能示例
Aug 07 Python
python使用tkinter库实现五子棋游戏
Jun 18 Python
200行python代码实现2048游戏
Jul 17 Python
基于Python实现大文件分割和命名脚本过程解析
Sep 29 Python
python类中super() 的使用解析
Dec 19 Python
JetBrains PyCharm(Community版本)的下载、安装和初步使用图文教程详解
Mar 19 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
使用Smarty 获取当前日期时间和格式化日期时间的方法详解
2013/06/18 PHP
PHP文件上传判断file是否己选择上传文件的方法
2014/11/10 PHP
php实现使用正则将文本中的网址转换成链接标签
2014/12/03 PHP
JavaScript 替换Html标签实现代码
2009/10/14 Javascript
JavaScript在多浏览器下for循环的使用方法
2012/11/07 Javascript
浅谈Javascript的静态属性和原型属性
2015/05/07 Javascript
JS简单实现无缝滚动效果实例
2016/08/24 Javascript
Vuejs第十一篇组件之slot内容分发实例详解
2016/09/09 Javascript
mint-ui在vue中的使用示例
2018/04/05 Javascript
详解一个基于react+webpack的多页面应用配置
2019/01/21 Javascript
详解用JS添加和删除class类名
2019/03/25 Javascript
微信小程序点击列表跳转到对应详情页过程解析
2019/09/26 Javascript
JQuery事件委托(适用于给动态生成的脚本元素添加事件)
2020/02/01 jQuery
关于vue 结合原生js 解决echarts resize问题
2020/07/26 Javascript
解决vant框架做H5时踩过的坑(下拉刷新、上拉加载等)
2020/11/11 Javascript
[15:23]教你分分钟做大人:虚空假面
2014/10/30 DOTA
Linux下使用python调用top命令获得CPU利用率
2015/03/10 Python
python3 线性回归验证方法
2019/07/09 Python
python中bs4.BeautifulSoup的基本用法
2019/07/27 Python
python3爬取torrent种子链接实例
2020/01/16 Python
PyTorch的torch.cat用法
2020/06/28 Python
使用CSS3的ruby-position固定注音位置的用法示例
2016/07/05 HTML / CSS
HTML5使用ApplicationCache接口实现离线缓存技术解决离线难题
2012/12/13 HTML / CSS
英国一家专门出售品牌鞋子的网站:Allsole
2016/08/07 全球购物
美国在线肉类和海鲜配送:Crowd Cow
2020/10/02 全球购物
会计电算一体化个人简历的自我评价
2013/10/15 职场文书
骨干教师培训方案
2014/05/06 职场文书
计算机专业自荐信范文
2014/05/28 职场文书
卫生标语大全
2014/06/21 职场文书
综合素质自我评价怎么写
2014/09/14 职场文书
个人四风问题原因分析及整改措施
2014/09/28 职场文书
公司离职证明标准格式
2014/11/18 职场文书
沂蒙六姐妹观后感
2015/06/08 职场文书
教您:房贷工资收入证明应该怎么写?
2019/08/19 职场文书
浅谈golang 中time.After释放的问题
2021/05/05 Golang
SpringBoot详解整合Redis缓存方法
2022/07/15 Java/Android