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

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

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

相关推荐

安全教育登录入口平台(安全教育登录入口平台官网)

122交通安全教育怎么登录:122交通网的注册方法是首先登录网址http://www.122.cn/,接着打开网页后,点击右上角的“个人登录”;其次进入邮箱注册,然后进入到注册页面,输入相关信息即可完...

大鱼吃小鱼经典版(大鱼吃小鱼经典版(经典版)官方版)

大鱼吃小鱼小鱼吃虾是于谦跟郭麒麟的《我的棒儿呢?》郭德纲说于思洋郭麒麟作诗的相声,最后郭麒麟做了一首,师傅躺在师母身上大鱼吃小鱼小鱼吃虾虾吃水水落石出师傅压师娘师娘压床床压地地动山摇。...

谷歌地球下载高清卫星地图(谷歌地球地图下载器)
  • 谷歌地球下载高清卫星地图(谷歌地球地图下载器)
  • 谷歌地球下载高清卫星地图(谷歌地球地图下载器)
  • 谷歌地球下载高清卫星地图(谷歌地球地图下载器)
  • 谷歌地球下载高清卫星地图(谷歌地球地图下载器)
哪个软件可以免费pdf转ppt(免费的pdf转ppt软件哪个好)
哪个软件可以免费pdf转ppt(免费的pdf转ppt软件哪个好)

要想将ppt免费转换为pdf的话,我们建议大家可以下一个那个wps,如果你是会员的话,可以注册为会员,这样的话,在wps里面的话,就可以免费将ppt呢转换为pdfpdf之后呢,我们就可以直接使用,不需要去直接不需要去另外保存,为什么格式转...

2026-02-04 09:03 off999

电信宽带测速官网入口(电信宽带测速官网入口app)

这个网站看看http://www.swok.cn/pcindex.jsp1.登录中国电信网上营业厅,宽带光纤,贴心服务,宽带测速2.下载第三方软件,如360等。进行在线测速进行宽带测速时,尽...

植物大战僵尸95版手机下载(植物大战僵尸95 版下载)

1可以在应用商店或者游戏平台上下载植物大战僵尸95版手机游戏。2下载教程:打开应用商店或者游戏平台,搜索“植物大战僵尸95版”,找到游戏后点击下载按钮,等待下载完成即可安装并开始游戏。3注意:确...

免费下载ppt成品的网站(ppt成品免费下载的网站有哪些)

1、Chuangkit(chuangkit.com)直达地址:chuangkit.com2、Woodo幻灯片(woodo.cn)直达链接:woodo.cn3、OfficePlus(officeplu...

2025世界杯赛程表(2025世界杯在哪个国家)

2022年卡塔尔世界杯赛程公布,全部比赛在卡塔尔境内8座球场举行,2022年,决赛阶段球队全部确定。揭幕战于当地时间11月20日19时进行,由东道主卡塔尔对阵厄瓜多尔,决赛于当地时间12月18日...

下载搜狐视频电视剧(搜狐电视剧下载安装)

搜狐视频APP下载好的视频想要导出到手机相册里方法如下1、打开手机搜狐视频软件,进入搜狐视频后我们点击右上角的“查找”,找到自已喜欢的视频。2、在“浏览器页面搜索”窗口中,输入要下载的视频的名称,然后...

pubg免费下载入口(pubg下载入口官方正版)
  • pubg免费下载入口(pubg下载入口官方正版)
  • pubg免费下载入口(pubg下载入口官方正版)
  • pubg免费下载入口(pubg下载入口官方正版)
  • pubg免费下载入口(pubg下载入口官方正版)
永久免费听歌网站(丫丫音乐网)

可以到《我爱音乐网》《好听音乐网》《一听音乐网》《YYMP3音乐网》还可以到《九天音乐网》永久免费听歌软件有酷狗音乐和天猫精灵,以前要跳舞经常要下载舞曲,我从QQ上找不到舞曲下载就从酷狗音乐上找,大多...

音乐格式转换mp3软件(音乐格式转换器免费版)

有两种方法:方法一在手机上操作:1、进入手机中的文件管理。2、在其中选择“音乐”,将显示出手机中的全部音乐。3、点击“全选”,选中所有音乐文件。4、点击屏幕右下方的省略号图标,在弹出菜单中选择“...

电子书txt下载(免费的最全的小说阅读器)

1.Z-library里面收录了近千万本电子书籍,需求量大。2.苦瓜书盘没有广告,不需要账号注册,使用起来非常简单,直接搜索预览下载即可。3.鸠摩搜书整体风格简洁清晰,书籍资源丰富。4.亚马逊图书书籍...

最好免费观看高清电影(播放免费的最好看的电影)

在目前的网上选择中,IMDb(互联网电影数据库)被认为是最全的电影网站之一。这个网站提供了各种类型的电影和电视节目的海量信息,包括剧情介绍、演员表、评价、评论等。其还提供了有关电影制作背后的详细信息,...

孤单枪手2简体中文版(孤单枪手2简体中文版官方下载)

要将《孤胆枪手2》游戏的征兵秘籍切换为中文,您可以按照以下步骤进行操作:首先,打开游戏设置选项,通常可以在游戏主菜单或游戏内部找到。然后,寻找语言选项或界面选项,点击进入。在语言选项中,选择中文作为游...

取消回复欢迎 发表评论: