百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Python 静态方法和类方法的区别(简述python中类方法和静态方法)

off999 2024-09-20 22:49 51 浏览 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

相关推荐

word密钥激活码2016(word 2016激活码)

1、office2016包含word、excel、powerpoint等组件,直接使用office2016密钥就能激活word2016。2、如果你安装的是word2016独立组件,也有独立的word2...

360重装系统只是重装c盘吗(360重装系统需要u盘吗)

在选择还原盘符时,软件默认为C盘,只要不是误操作或刻意为之,则系统只会安装到C盘。在安装系统完成后,先安装安全软件如360安全卫士加360杀毒或者金山毒霸之类其它安全软件,进行全盘查杀木马、病毒,再打...

电脑不断的重启是怎么回事(电脑在不断重启怎么回事)

1、系统出现问题系统如果丢失文件,缺少某种关键的注册表信息的话,是会出现不断重启的现象的。这种情况我们只需要重装系统即可。2、电脑硬盘损坏硬盘如果出现坏道,进水也会出现不断重启的现象。这个时候我们就需...

联想小新700(联想小新700电竞版配置)

小新700-15isk采用15.6英寸1920x1080分辨率全高清IPS雾面防眩光屏,通过莱茵TUV低蓝光认证,全段DC调光无频闪,100%sRGB的高色域覆盖,300尼特,摄像头升级至1080P全...

手机声卡软件免费下载(手机声卡软件有哪些)

要下载和安装声卡驱动程序,您可以按照以下步骤进行操作:1.确定您的声卡型号和制造商。您可以在计算机的设备管理器中找到这些信息。2.访问制造商的官方网站。在其支持或驱动程序下载页面上,搜索您的声卡型...

tplogin管理员初始密码(tplogincn管理员默认密码)

admin。tplogincn管理员密码是admin。tplogin.cn是TP-Link(普联)无线路由器的管理页面地址,页面中需要输入的管理员密码是admin。注意:如果输入admin后路由器没有...

nvidia驱动更新在哪里(nvidia驱动更新有用吗)

N卡显卡驱动可以在官网更新。通常情况下,N卡显卡的驱动可以通过官方网站进行更新,它们会定期发布新的驱动程序以解决已知或新发现的问题,而且官网更新的驱动程序可以有效地解决很多显卡问题。此外,如果您不知道...

u盘量产工具安卓版(u盘量产工具使用教程)

万能u盘量产工具。金士顿U盘量产工具可以改写U盘主控芯片数据实现U盘量产还原修复的功效。用户只需要将U盘插入计算机,使用金士顿U盘修复软件扫描修复和量产即可恢复。原理是重写和还原U盘的主控芯片数据,让...

ghost纯净版哪个网站(ghost 正版)

windows7ghost纯净版特色:1、专业为电脑制作,定制版系统使笔记本电脑运行更加可靠。2、安装盘经过多名电脑安装人员测试,稳定性和兼容性非常好。3、通过多台不同硬件型号的计算机测试,没有蓝屏,...

联想笔记本电脑怎么连接无线网wifi

答:联想笔记本电脑连接无线网wifi的方法:1在桌面右键点击“网上邻居”,选择属性菜单。2.后右键单击“无线网络连接”选择“属性”,进入无线网络连接属性对话框。3.在可用无线连接列表里找到对应的佰网络...

一键ghost xp下载和安装(一键ghost在哪下载)

在xp系统下运行,点击开始-程序-一键GHOST,软件运行后会自动识别当前系统状态,根据不同情况(C盘映像是否存在)自动定位到不同的选项:1、如果不存在GHO文件,则自动定位到"备份"...

一键重装系统怎么删除(开机系统之家一键重装系统怎么删除)

第一种方法:正常选择系统进入后,您可以直接打开小白一键重装系统软件,在软件的其它设置选项中有个启动菜单,在这里您可以找到需要删除的开机引导菜单删除即可。第二种方法:正常开机进入Windows系统,...

directx 11官方下载(directx11官网)
directx 11官方下载(directx11官网)

要在官网下载DX11,首先需要访问Microsoft的官方下载中心,并在搜索框中输入"DirectX11"。然后,选择适合操作系统的版本(一般都是Windows7和以上),下载并安装。注意,在下载前最好确保系统已经更新到...

2026-01-05 06:03 off999

一键清除系统垃圾(系统自带的一键清理垃圾有用吗)
一键清除系统垃圾(系统自带的一键清理垃圾有用吗)

清理电脑的缓存垃圾和深度清理,保证电脑运行速度1、鼠标右键单击,新建文本文档2,在文件中输入源代码echo正在清除系统垃圾文件,请稍等......del/f/s/q%systemdrive%\*.tmpdel/f/s/q...

2026-01-05 05:51 off999

win10更新系统要多久(win10更新大概要多久)

15-35分钟,根据电脑配置不同,时间也不同。win10;Windows10是美国微软公司所研发的新一代跨平台及设备应用的操作系统。在正式版本发布后的一年内,所有符合条件的Windows7、Win...

取消回复欢迎 发表评论: