Python中的类方法和静态
2015-11-23 17:40
561 查看
原文:http://clojure.cn/python中的类方法和静态/
转载自: http://www.tuicool.com/articles/yqmm6fu
这也不是什么难点,写一下就是感觉网上有些写得不太明白,其实不用多深入探讨,可以简单的知道区别只有如下即可:
1,普通方法须用对象调用,默认第一个参数会传入对象自身(这个“自身”习惯上用一个名为self的变量表示,其实无所谓名字,虽然贫道并不推荐改成其他)。
2,类方法可以使用对象或者类调用,类似普通方法,默认第一个参数传入类方法所在的类而不是对象(同上习惯上用cls表示)。
3,静态方法可以使用对象或者类调用,并没有默认传入的方法。
下面看个例子:
输出还是很明白的,不多说了:
<__main__.Demo object at 0x7f4f41e47c90> 139978384637072 a (‘b’,) {‘c’: ‘c’}
<class ‘__main__.Demo’> 15255136 a (‘b’,) {‘c’: ‘c’}
<class ‘__main__.Demo’> 15255136 a (‘b’,) {‘c’: ‘c’}
a (‘b’,) {‘c’: ‘c’}
a (‘b’,) {‘c’: ‘c’}
转载自: http://www.tuicool.com/articles/yqmm6fu
这也不是什么难点,写一下就是感觉网上有些写得不太明白,其实不用多深入探讨,可以简单的知道区别只有如下即可:
1,普通方法须用对象调用,默认第一个参数会传入对象自身(这个“自身”习惯上用一个名为self的变量表示,其实无所谓名字,虽然贫道并不推荐改成其他)。
2,类方法可以使用对象或者类调用,类似普通方法,默认第一个参数传入类方法所在的类而不是对象(同上习惯上用cls表示)。
3,静态方法可以使用对象或者类调用,并没有默认传入的方法。
下面看个例子:
class Demo(object): def regular_method(self, arg, *args, **kwargs): print self, id(self), arg, args, kwargs @classmethod def class_method(cls, arg, *args, **kwargs): print cls, id(cls), arg, args, kwargs @staticmethod def static_method(arg, *args, **kwargs): print arg, args, kwargs demo = Demo() demo.regular_method("a", "b", c = "c") demo.class_method("a", "b", c = "c") Demo.class_method("a", "b", c = "c") demo.static_method("a", "b", c = "c") Demo.static_method("a", "b", c = "c")
输出还是很明白的,不多说了:
<__main__.Demo object at 0x7f4f41e47c90> 139978384637072 a (‘b’,) {‘c’: ‘c’}
<class ‘__main__.Demo’> 15255136 a (‘b’,) {‘c’: ‘c’}
<class ‘__main__.Demo’> 15255136 a (‘b’,) {‘c’: ‘c’}
a (‘b’,) {‘c’: ‘c’}
a (‘b’,) {‘c’: ‘c’}
相关文章推荐
- 2.1.5 Python方法详解
- [Python]Flask构建网站分析应用
- [Python]Flask构建网站分析应用
- Python 基础
- python环境准备以及easy_install和pip的安装
- python: 从函数了解到装饰器
- python编码问题之——Decode error - output not utf-8
- [python]文档字符串
- python 学习 (type)
- <LeetCode><Hard> 4 Median of Two Sorted Arrays
- Python抓取百度贴吧网页信息以及代码下载
- python try 代码组检测错误和异常
- python遗传算法实现数据拟合
- PyCharm下集成PyLint
- 首次与python的感想
- 欢迎使用CSDN-markdown编辑器
- python游戏编程——跟13岁儿童学编程
- Python的一点使用心得
- python 收email实例 -解决标题和正文的中文显示
- python 在MySQL中的模糊匹配