Python静态方法(staticmethod)和类方法(classmthod)区别
来源:互联网 发布:如何加入淘宝热卖 编辑:程序博客网 时间:2024/06/06 08:49
因为对方法和函数两者概念有些混淆,所以研究了一下。后来顺带把静态方法和类方法也摸索了一下,稍微有了一些感觉。
直接上代码:
# coding:utf-8class Apple: def fun1(self): return 'normal' @staticmethod def fun2(): return 'staticmethod' @classmethod def fun3(cls): return 'classmethod'print Apple.fun1print Apple.fun2print Apple.fun3print "-"*80apple = Apple()print apple.fun1print apple.fun2print apple.fun3print "-"*80apple1 = Apple()print apple1.fun1print apple1.fun2print apple1.fun3
运行结果:
<unbound method Apple.fun1><function fun2 at 0x00000000022FC4A8><bound method classobj.fun3 of <class __main__.Apple at 0x0000000001E7C768>>--------------------------------------------------------------------------------<bound method Apple.fun1 of <__main__.Apple instance at 0x00000000022FAE08>><function fun2 at 0x00000000022FC4A8><bound method classobj.fun3 of <class __main__.Apple at 0x0000000001E7C768>>--------------------------------------------------------------------------------<bound method Apple.fun1 of <__main__.Apple instance at 0x00000000022FAE48>><function fun2 at 0x00000000022FC4A8><bound method classobj.fun3 of <class __main__.Apple at 0x0000000001E7C768>>
- 普通方法传入的第一个参数必须是self(当然也可以不用self,官方要求尽量用self),self是指实例对象本身;
- 静态方法无需传参;
- 类方法传入的第一个参数必须是class,是指类本身。
对比结果1,5,9行
fun1通过class调用时,它是未绑定的方法,而实例化apple和apple1之后,它属于绑定的方法,且实例化后的apple和apple1内存地址不同,因为它们属于不同的实例对象。
对比结果2,6,10行
静态方法fun2通过class调用或者通过实例化后的对象调用,是没有任何区别的,全部都是指向同一块内存地址。可以简单的理解成静态方法与类或者实例没有任何关系,一旦调用后,它的内存地址即确定。
对比结果3,7,11行
类方法fun3通过class调用或者通过实例化后的对象调用,是没有任何区别的,全部都是指向同一块内存地址。为什么?因为实例化对象apple和apple1调用类方法fun3传入的第一个参数是类本身Apple,也就是说apple.fun3 = apple1.fun3 = Apple.fun3。
区别总结:
- 静态方法装饰器下定义的方法属于函数(function);
- 类方法装饰器下定义的方法属于方法(method);
- 静态方法无需传入任何参数;
- 类方法传入的第一个参数必须是class本身cls;
- 静态方法与类方法一旦被调用,内存地址即确定。通过类调用和通过实例化对象调用的结果完全一样。
阅读全文
1 0
- Python静态方法(staticmethod)和类方法(classmthod)区别
- Python 静态方法 @staticmethod
- python 静态方法staticmethod和类方法classmethod
- 静态方法和类方法, staticmethod & classmethod
- 我所理解的实例方法、类方法(@classmethod)和静态方法(@staticmethod)(关键词:实例方法/类方法/@classmethod/静态方法/@staticmethod)
- @classmethod类放和@staticmethod静态方法
- python-静态方法staticmethod、类方法classmethod、属性方法property
- python的静态方法以及@staticmethod或@classmethod的区别
- Python中staticmethod方法和classmethod方法区别
- python之静态和类方法:staticmethod和classmethod内置函数
- python 中 @classmethod 、staticmethod 和 普通方法 的区别
- python中 classmethod、staticmethod和普通方法的区别
- python 类中@staticmethod,@classmethod和实例方法
- Python 实例方法、@staticmethod和@classmethod
- Python 实例方法、@staticmethod和@classmethod
- Python 实例方法、@staticmethod和@classmethod
- python的classmethod和staticmethod方法
- Python 实例方法、@staticmethod和@classmethod
- The Accomodation of Students
- 嵌入式WebSocket的实现
- HEVC_帧内
- POJ
- SpringMVC与Struts2 的区别!
- Python静态方法(staticmethod)和类方法(classmthod)区别
- JAVA 实现队列功能
- POJ 2823 Sliding Window(单调队列)
- python学习笔记之004.py
- Spark集群工作异常,无法读取Hadoop集群文件处理办法
- yii2.0-captcha验证码--详细设置
- 【深入理解Java虚拟机学习笔记】虚拟机类加载机制
- 一台电脑安装多个mysql(mysql修改密码)
- 解决BCGControlbar中Ribbon界面主按钮一直显示File的问题