Python 静态方法和类方法的区别(简述python中类方法和静态方法)
off999 2024-09-20 22:49 48 浏览 0 评论
例子 – 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 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。
点击居然老师公开课视频播放地址
链接:https://www.jianshu.com/p/165e33ebc2ca
相关推荐
- 电脑开机进入桌面就蓝屏(电脑开机进去桌面就蓝屏)
-
步骤1、如果发现开机蓝屏时,可能以通过开机第一屏时迅速不停按动F8键,在屏幕出来的界面选择[安全模式]并按[Enter]进入安全模式。【电脑一开机就蓝屏】步骤1 步骤2、如果能进安全模式,说明软件有...
-
- 惠普打印机程序驱动官网(中国惠普打印机驱动程序)
-
hp打印机驱动程序可以去惠普官网下载,然后安装驱动程序1/6登陆www.hp.com.cn,点击右上角的“支持”,选择“软件与驱动程序”2/6点击左侧“按产品类别浏览”中的“打印机”3/6输入要查询的产品编号4/6点击左侧搜索结...
-
2025-12-30 14:03 off999
- 一键装机之家官网(一键装机软件哪个好用)
-
http://www.xitongzhijia.net/系统之家官网打造的系统之家装机大师,使用很简单,可以用U盘装系统,也可以一键重装系统,可以帮助你快速升级到你想要升级的系统。系统之家装机大师是一...
- 显示桌面图标不见了怎么恢复
-
1、在电脑桌面上,点击鼠标右键。2、在右键菜单中,点击“查看”。3、在“查看”的下一级菜单中,点击“显示桌面图标”,即可显示出桌面图标。4、用鼠标右键点击任务栏。5、在右键菜单中,点击“任务管理器”。...
- 芯片排行(麒麟芯片排行)
-
2021世界十大芯片公司排名1.英特尔成立于1968年,一直都处于领先地位,是最著名的计算机和中央处理器创造商。2.三星成立于1938年,三星涉及了许多领域,比如手机、电脑和各种电子半导体领域。3.英...
- win7系统进入桌面黑屏(win7进去界面后黑屏)
-
win7黑屏无法进入桌面的解决方法:1、按【ctrl+alt+del】组合键,打开任务管理器;2、依次点击文件、创建新任务,输入regedit;3、在打开的注册表编辑器中,找到shell选项,更改数值...
- 文件隐藏专家(文件隐藏专家怎么设置)
-
是隐藏的软件恢复到桌面吗?在手机桌面中间向上滑→桌面设置→应用隐藏/私密应用→输入密码→编辑→选择应用点击即可取消。 默认F2可以开始,停止的。亦可以自己设置。 屏幕录像专家设置步骤: 1、在电...
- 电脑蓝屏无法重启怎么办(电脑蓝屏重启不行)
-
插上U盘并重启电脑。大多数电脑都可以通过按下F11或F12来选择U盘启动。·在启动时选择U盘启动,然后按回车键。接着选择“第二项”,开始启动PE系统。·现在已经进入PE系统了,找到引导修复工具并双击。...
- tplink路由器重设密码步骤(tplink路由器重置密码设置步骤图解)
-
重设TP-LINK无线路由器密码方法如下1、打开浏览器,在地址栏输入192.168.1.1(一般路由器地址是这个或者查看路由器背面的登录信息)进路由-输入用户名,密码,(默认一般是admin)。2、...
-
- 查看电脑ip地址的命令(查看电脑ip地址用什么命令)
-
1、在“本地连接”的状态中查看。2、使用“ipconfig/all”命令查看。3、打开电脑网页,输入IP地址,点击确定,就能看到本机IP。扩展资料IP地址(InternetProtocolAddress),全称为网际协议地址,是一种在...
-
2025-12-30 10:03 off999
- ie浏览器9(IE浏览器9.0如何升级)
-
1、首先,我们点击开始菜单,找到控制面板,点击一下。2、之后,找到程序和功能选项,点击一下。3、点击进入后,我们找到左边的打开或关闭windows功能,点击一下。4、点击进入后,找到Internet...
- hp1020打印机驱动怎么下载(hp1020打印机驱动怎么下载)
-
惠普1020打印机驱动怎么安装: 1.首先到下载软件名称:惠普1020打印机驱动程序官方版(支持win7/8)32位/64位软件大小:5.09MB更新时间:2014-09-05立即下载 2.然后...
- win2003是windows7系统(win2003哪个版本好)
-
win2003是专门用于服务器的操作系统,现在最主流的windows服务器系统主要是win2003server和win2008server,winXP是个人电脑专用的操作系统,现在微软已经不再提供XP...
欢迎 你 发表评论:
- 一周热门
-
-
抖音上好看的小姐姐,Python给你都下载了
-
全网最简单易懂!495页Python漫画教程,高清PDF版免费下载
-
Python 3.14 的 UUIDv6/v7/v8 上新,别再用 uuid4 () 啦!
-
飞牛NAS部署TVGate Docker项目,实现内网一键转发、代理、jx
-
python入门到脱坑 输入与输出—str()函数
-
宝塔面板如何添加免费waf防火墙?(宝塔面板开启https)
-
Python三目运算基础与进阶_python三目运算符判断三个变量
-
(新版)Python 分布式爬虫与 JS 逆向进阶实战吾爱分享
-
失业程序员复习python笔记——条件与循环
-
系统u盘安装(win11系统u盘安装)
-
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)
