1.形式上的异同点:

在形式上,Python中:实例方法必须有self,类方法用@classmethod装饰必须有cls,静态方法用@staticmethod装饰不必加cls或self,如下代码所示:

 class A(object):
def __init__(self, name):
self.name = name def get_a_object(self):
return "get object method:{}".format(self.name) @staticmethod
def get_b_static():
return "get static method" @classmethod
def get_c_class(cls):
return "get class method" a = A(name="method")
print("{} by object method".format(a.get_a_object()))
try:
print(A.get_a_object())
except Exception:
print("Class can not call the instance method directly by class method")
print("{} by class method".format(A.get_b_static()))
print("{} by object method".format(a.get_b_static()))
print("{} by class method".format(A.get_c_class()))
print("{} by object method".format(a.get_c_class()))

执行结果:

get object method:method by object method
Class can not call the instance method directly by class method
get static method by class method
get static method by object method
get class method by class method
get class method by object method

从执行结果可以看出,实例方法必须实例化后调用不可用类点方法直接调用,静态方法和类方法既可以用实例点方法调用也可用类点方法直接调用

2.应用场景及本质上的异同点

对于应用场景上异同点主要是比较类方法和静态方法,先看一段代码:

 class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day @staticmethod
def today_static():
t = time.localtime()
return Date(t.tm_year, t.tm_mon, t.tm_mday) @classmethod
def today(cls):
t = time.localtime()
return cls(t.tm_year, t.tm_mon, t.tm_mday) class NewDate(Date):
pass date = Date(2018, 12, 31)
new_data = NewDate(2018,12,31) print("class method -------------")
print(date.today().__class__)
print(Date.today().__class__)
print(NewDate.today().__class__)
print(new_data.today().__class__)
print("\n")
print("static method ------------")
print(date.today_static().__class__)
print(Date.today_static().__class__)
print(NewDate.today_static().__class__)
print(new_data.today_static().__class__)
Date类有year、month、day三个属性,静态方法today_static,类方法today,
NewDate类继承于Date,分别打印调用类方法和静态方法时属于哪个类
class method -------------
<class '__main__.Date'>
<class '__main__.Date'>
<class '__main__.NewDate'>
<class '__main__.NewDate'> static method ------------
<class '__main__.Date'>
<class '__main__.Date'>
<class '__main__.Date'>
<class '__main__.Date'>

通过结果可以看出:对于类方法today,调用Date.today()时cls=Date,调用NewDate.today()时,cls=NewDate,cls跟随调用类的变化而变化;对于静态方法today_static,指定了Date(t.tm_year, t.tm_mon, t.tm_mday),所以所属的类始终是Data,如果将Date改为:

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

此时对于@classmethod不会有任何变化,但是对于@staticmethod 如果today_static 返回值不是Date1(t.tm_year, t.tm_mon, t.tm_mday),则会报错

python中@staticmethod、@classmethod和实例方法的更多相关文章

  1. python中staticmethod classmethod及普通函数的区别

    staticmethod 基本上和一个全局函数差不多,只不过可以通过类或类的实例对象 (python里光说对象总是容易产生混淆, 因为什么都是对象,包括类,而实际上 类实例对象才是对应静态语言中所谓对 ...

  2. 【python】Python 中的 classmethod 和 staticmethod

    Python 中的 classmethod 和 staticmethod 有什么具体用途? 推荐地址:http://www.cnblogs.com/wangyongsong/p/6750454.htm ...

  3. 基于python中staticmethod和classmethod的区别(详解)

    例子 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 class A(object):   def foo(self,x):     print "executing foo ...

  4. 关于Python中的classmethod

    Python 中的 classmethod classmethod: 作用是直接将自己的类对象,传给类方法. 一.classmethod 1)不用classmethod的时候 你的代码可能是这样写的, ...

  5. python中 staticmethod与classmethod

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

  6. python 类中staticmethod,classmethod,普通方法

    1.staticmethod:静态方法和全局函数类似,但是通过类和对象调用. 2.classmethod:类方法和类相关的方法,第一个参数是class对象(不是实例对象).在python中class也 ...

  7. Python中的类方法、实例方法、静态方法

    类方法 @classmethod 在python中使用较少,类方法传入的第一个参数是 cls,是类本身: 类方法可以通过类直接调用或者通过实例直接调用,但无论哪种调用方式,最左侧传入的参数一定是类本身 ...

  8. python中@staticmethod与@classmethod

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

  9. Python 中的 classmethod 和 staticmethod 有什么具体用途?

    作者:李保银链接:https://www.zhihu.com/question/20021164/answer/18224953来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明 ...

随机推荐

  1. Windows平台下,Java性能分析工具VisualVM的Tomcat8的配置

    VisualVM在JDK6版本及以上已经自带这个应用. 位置:C:\Program Files (x86)\Java\jdk1.8.0_60\bin\jvisualvm.exe   在Windows环 ...

  2. 打包APP

    记得之前网上也有app打包平台,但是都会有所限制,或者增加广告等等,这里呢,介绍一款工具,可以自己将网站打包成app. wex5 (WeX5开源免费跨端开发工具-html5 app开发就用WeX5)官 ...

  3. Confluence 6 管理协同编辑 - 审计的考虑

    我们知道一些客户对审计是主要考虑的方面.我们不能保证在协同编辑的时候具有审计,审查功能.所有页面的修改当前附加到用户发布页面的属性中而不是用户的特定修改. 如果这个对你来说是一个问题的话,我们建议你在 ...

  4. Confluence 6 workbox 的位置

    Confluence 6 workbox 的位置在首页什么地方? workbox 应该在页面顶部的用户登录后的地方. https://www.cwiki.us/display/CONFLUENCEWI ...

  5. Sublime Text 3 快捷键总结(拿走)

    以下是个人总结不完全的快捷键总汇,祝愿各位顺利解放自己的鼠标. 选择类 Ctrl+D 选中光标所占的文本,继续操作则会选中下一个相同的文本. Alt+F3 选中文本按下快捷键,即可一次性选择全部的相同 ...

  6. social psychology 10th David G. Myers

    Social psychology is a science that studies the influences of our situations, with special attention ...

  7. Task.Run()任务执行

    1)Task本身就是异步执行的(4.5的那个类). 2)控制数量和终止线程问题可以考虑这个模式: static async void RunAsync() { CancellationTokenSou ...

  8. k8s中的api server的ca证书,可以和front proxy ca证书一样么?

    答案是: 绝对不可以! 因为请求先验证的是 --requestheader-client-ca-file CA 然后才是--client-ca-file. . 那获取的用户名就会通不过了. 所以会影响 ...

  9. Inflated 3D ConvNet 【I3D】

    Two-Stream Inflated 3D ConvNet (I3D) HMDB-51: 80.9% and UCF-101: 98.0% 在Inception-v1 Kinetics上预训练 Co ...

  10. java web获取请求体内容

    Java Web中如何获取请求体内容呢? 我们知道请求方式分为两种:Get,Post. /*** * Compatible with GET and POST * * @param request * ...