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使用tensorflow保存、加载和使用模型的方法
Jan 31 Python
python实现监控某个服务 服务崩溃即发送邮件报告
Jun 21 Python
pygame游戏之旅 创建游戏窗口界面
Nov 20 Python
pyqt 实现为长内容添加滑轮 scrollArea
Jun 19 Python
python如何实现异步调用函数执行
Jul 08 Python
Python配置文件处理的方法教程
Aug 29 Python
Python OrderedDict的使用案例解析
Oct 25 Python
python正则过滤字母、中文、数字及特殊字符方法详解
Feb 11 Python
Python的赋值、深拷贝与浅拷贝的区别详解
Feb 12 Python
Python 实现使用空值进行赋值 None
Mar 12 Python
python3中确保枚举值代码分析
Dec 02 Python
浅析Python中的套接字编程
Jun 22 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 导出数据到淘宝助手CSV的方法分享
2010/02/27 PHP
PHP与javascript实现变量交互的示例代码
2013/07/23 PHP
PHP生成自适应大小的缩略图类及使用方法分享
2014/05/06 PHP
PHP正则匹配日期和时间(时间戳转换)的实例代码
2016/12/14 PHP
php微信公众号开发(4)php实现自定义关键字回复
2016/12/15 PHP
PHP静态延迟绑定和普通静态效率的对比
2017/10/20 PHP
jquery.combobox中文api和例子,修复了上面的小bug
2011/03/28 Javascript
jquery做的一个简单的屏幕锁定提示框
2014/03/26 Javascript
JavaScript闭包函数访问外部变量的方法
2014/08/27 Javascript
jQuery 1.9.1源码分析系列(十三)之位置大小操作
2015/12/02 Javascript
微信小程序 开发之全局配置
2017/05/05 Javascript
vue-router路由与页面间导航实例解析
2017/11/07 Javascript
详解node.js中的npm和webpack配置方法
2018/01/21 Javascript
VUE2.0+ElementUI2.0表格el-table循环动态列渲染的写法详解
2018/11/30 Javascript
Vue快速实现通用表单验证功能
2019/12/05 Javascript
JavaScript数组排序功能简单实现
2020/05/14 Javascript
小程序瀑布流组件实现翻页与图片懒加载
2020/05/19 Javascript
JS实现购物车基本功能
2020/11/08 Javascript
python转换字符串为摩尔斯电码的方法
2015/07/06 Python
Python字符串切片操作知识详解
2016/03/28 Python
Python使用Selenium+BeautifulSoup爬取淘宝搜索页
2018/02/24 Python
Python第三方Window模块文件的几种安装方法
2018/11/22 Python
对Python Class之间函数的调用关系详解
2019/01/23 Python
python使用pandas处理大数据节省内存技巧(推荐)
2019/05/05 Python
python文件选择对话框的操作方法
2019/06/27 Python
通过python实现随机交换礼物程序详解
2019/07/10 Python
python批量读取文件名并写入txt文件中
2020/09/05 Python
如何基于python操作json文件获取内容
2019/12/24 Python
django实现模板中的字符串文字和自动转义
2020/03/31 Python
python实现跨年表白神器--你值得拥有
2021/01/04 Python
Crocs美国官方网站:卡骆驰洞洞鞋
2017/08/04 全球购物
水污染治理工程专业求职信
2014/06/14 职场文书
义务教育学校标准化建设汇报材料
2014/08/16 职场文书
计算机实训报告范文
2014/11/05 职场文书
python开发的自动化运维工具ansible详解
2021/08/07 Python
Python+OpenCV实现在图像上绘制矩形
2022/03/21 Python