原文:https://blog.csdn.net/youngbit007/article/details/68957848

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/youngbit007/article/details/68957848
classmethod:类方法
staticmethod:静态方法

在Python中,静态方法和类方法都是可以通过类对象和类对象实例访问。但是区别是:

@classmethod 是一个函数修饰符,它表示接下来的是一个类方法,而对于平常我们见到的则叫做实例方法。 类方法的第一个参数cls,而实例方法的第一个参数是self,表示该类的一个实例。

普通对象方法至少需要一个self参数,代表类对象实例

类方法有类变量cls传入,从而可以用cls做一些相关的处理。并且有子类继承时,调用该类方法时,传入的类变量cls是子类,而非父类。

对于类方法,可以通过类来调用,就像C.f(),有点类似C++中的静态方法, 也可以通过类的一个实例来调用,就像C().f(),这里C(),写成这样之后它就是类的一个实例了。

静态方法则没有,它基本上跟一个全局函数相同,一般来说用的很少

classmethod必须使用类对象作为第一个参数,而staticmethod则可以不传递任何参数。

class Date:

def __init__(self,day=0, month=0, year=0):
self.day=day
self.month = month
self.year = year

@classmethod
def from_string(cls, date_as_string):
day, month, year = map(int,date_as_string.split('-'))
my_date = cls(day, month, year)
return my_date

@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

if __name__ == '__main__':
my_date = Date.from_string('11-09-2012')
print(my_date.day, my_date.month,my_date.year)
is_date = Date.is_date_valid('13-13-2012')
print(is_date)

outputs:
11 9 2012
False
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
在来看另外的例子,为了验证有子类继承时,子类调用该类方法时,传入的类变量cls是子类,而非父类

class A:
@classmethod
def cm(cls):
print('类方法cm(cls)调用者:', cls.__name__)

@staticmethod
def sm():
print('静态方法sm()被调用')

class B(A):
pass

A.cm() # 类方法cm(cls)调用者: A
B.cm() # 类方法cm(cls)调用者: B
A.sm() # 静态方法sm()被调用
B.sm() # 静态方法sm()被调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
下面我们来看为什么要用到staticmethod与classmethod。

class Kls:
def __init__(self,data):
self.data = data
def printd(self):
print(self.data)

ik1=Kls('arun')
ik2=Kls('seema')
ik1.printd()
ik2.printd()

# 如果现在我们想写一些仅仅与类交互而不是和实例交互的方法会怎么样呢? 我们可以在类外面写一个简单的方法来做这些,
# 但是这样做就扩散了类代码的关系到类定义的外面. 如果像下面这样写就会导致以后代码维护的困难:
def get_no_of_instances(cls_obj):
return cls_obj.no_inst
class Kls:
no_inst = 0
def __init__(self):
Kls.no_inst = Kls.no_inst + 1
ik1 = Kls()
ik2 = Kls()
print(get_no_of_instances(Kls)) # 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
应用classmethod

class Kls(object):
no_inst = 0
def __init__(self):
Kls.no_inst = Kls.no_inst + 1
@classmethod
def get_no_of_instance(cls_obj):
return cls_obj.no_inst
ik1 = Kls()
ik2 = Kls()
print(ik1.get_no_of_instance())
print(Kls.get_no_of_instance())
# 2
# 2
1
2
3
4
5
6
7
8
9
10
11
12
13
@staticmethod
经常有一些跟类有关系的功能但在运行时又不需要实例和类参与的情况下需要用到静态方法

(转)python3-staticmethod与classmethod的更多相关文章

  1. (转)关于python3中staticmethod(静态方法)classmethod(类方法)实例方法的联系和区别

    原文:http://dmcoders.com/2017/08/30/pythonclass/ https://zhuanlan.zhihu.com/p/28010894------正确理解Python ...

  2. Python语言特性之3:@staticmethod和@classmethod

    问题:Python中@staticmethod和@classmethod两种装饰器装饰的函数有什么不同? 原地址:http://stackoverflow.com/questions/136097/w ...

  3. @staticmethod和@classmethod

    一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法. 而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用. 这有利于组织代码,把某些应 ...

  4. python(三)@staticmethod和@classmethod使用和区别

    转载自[1] 一般要用某个类的方法,先要实例这个类. 但是可以通过@staticmethod和@classmethod,直接用“类.方法()”来调用这个方法. 而 @staticmethod和@cla ...

  5. python @staticmethod和@classmethod的作用

    一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法. 而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用. 这有利于组织代码,把某些应 ...

  6. 手动实现staticmethod和classmethod装饰器

    首先,staticmethod和classmethod装饰器是通过非数据描述符实现的.用法简单,这里就不细说了. 这里主要分析一下staticmethod和classmethod是如何通过描述符实现的 ...

  7. python中@staticmethod与@classmethod

    @ 首先这里介绍一下‘@’的作用,‘@’用作函数的修饰符,是python2.4新增的功能,修饰符必须出现在函数定义前一行,不允许和函数定义在同一行.只可以对模块或者类定义的函数进行修饰,不允许修饰一个 ...

  8. python 之@staticmethod和@classmethod

    在python中,要调用一个类中的方法,一般的操作步骤如下: 1.实例化此类 2.调用此类中的方法 而@staticmethod和@classmethod则打破了这种引用方式,可以在不实例化类的情况下 ...

  9. python中 staticmethod与classmethod区别

    staticmethod与classmethod区别 参考 https://stackoverflow.com/questions/136097/what-is-the-difference-betw ...

  10. @staticmethod和@classmethod的作用与区别

    一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法. 而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用. 这有利于组织代码,把某些应 ...

随机推荐

  1. _ZSkill_快捷键_Xcode快捷键

    Xcode 快捷键使用 Command 用来导航,控制导航区域 Alt 控制右边的部分. 如Assistant Editor ,utility editor. Control 编辑区域上的jump b ...

  2. android 按照拼音模糊查询中如何把字符转换成拼音

    http://files.cnblogs.com/liaolandemengxiang/%E6%96%B0%E5%BB%BA%E6%96%87%E4%BB%B6%E5%A4%B9.rar 首先转换成的 ...

  3. Hdu4687 Boke and Tsukkomi

    Boke and Tsukkomi                                                                               Time ...

  4. bootstrap2.2相关文档

    本节课我们主要学习一下 Bootstrap表单和图片功能,通过内置的 CSS定义,显示各种丰富的效果. 一.表单 Bootstrap提供了一些丰富的表单样式供开发者使用. 1.基本格式 //实现基本的 ...

  5. Java学习--数组与方法

    1. public class MethodDemo01{ public static void main(String args[]){ printInfo() ; // 调用printInfo() ...

  6. Linux 下建立 SSH 隧道做 Socket 代理

    背景 需要解决本地访问内部集群中各台机器上的内部web服务,但是内部集群不能直接访问,只能通过edge node节点跳转. 前提:edge node可以通过ssh方式访问,在edge node上可以访 ...

  7. 在 Centos7 的KVM上启用嵌套虚拟化

    1.嵌套虚拟化意味着在虚拟机内配置虚拟化环境.换句话说,我们可以说嵌套虚拟化是虚拟机管理程序hypervisor的一个特性,它允许我们通过虚拟化管理程序(宿主机)的硬件加速在虚拟服务器内安装和运行虚拟 ...

  8. 什么是PAGELATCH和PAGEIOLATCH

    在分析SQL server 性能的时候你可能经常看到 PAGELATCH和PAGEIOLATCH.比方说 Select * from sys.dm_os_wait_stats 的输出里面就有Latch ...

  9. ajax调用WebMethed返回处理请求时出错

    ajax post调用WebMethed报错,返回的信息如下: {“Message”:“处理请求时出错”,“StackTrace”:“”,“ExceptionType”:“”} 查了一下WebMeth ...

  10. 【LA3485】 Bridge

    前言 哈哈哈,垃圾微积分哈哈哈 前置知识:自适应Simpson法与微积分初步,学会编程 Solution 考虑一下我们有的是什么: 一段桥梁的横向距离,悬线的长度,以及高度. 我们发现如果我们重新设一 ...