python @,@staticmethod,@classmethod
来源:互联网 发布:自学编程先看什么书 编辑:程序博客网 时间:2024/06/10 14:44
一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法。
而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用。
这有利于组织代码,把某些应该属于某个类的函数给放到那个类里去,同时有利于命名空间的整洁。
既然@staticmethod和@classmethod都可以直接类名.方法名()来调用,那他们有什么区别呢
从它们的使用上来看,- @staticmethod不需要表示自身对象的self和自身类的cls参数,就跟使用函数一样。
- @classmethod也不需要self参数,但第一个参数需要是表示自身类的cls参数。
如果在@staticmethod中要调用到这个类的一些属性方法,只能直接类名.属性名或类名.方法名。
而@classmethod因为持有cls参数,可以来调用类的属性,类的方法,实例化对象等,避免硬编码。
下面上代码:
class A(object): bar = 1 def foo(self): print 'foo' @staticmethod def static_foo(): print 'static_foo' print A.bar @classmethod def class_foo(cls): print 'class_foo' print cls.bar cls().foo()A.static_foo()A.class_foo()
阅读全文
0 0
- Python: classmethod & staticmethod 区别
- Python: classmethod & staticmethod 区别
- 】Python @classmethod @staticmethod
- python staticmethod和classmethod
- python classmethod staticmethod
- Python @staticmethod和@classmethod
- Python @classmethod @staticmethod
- python的staticmethod、classmethod
- Python staticmethod and classmethod
- 【转】Python @classmethod @staticmethod
- python staticmethod & classmethod
- python @ property classmethod staticmethod
- Python: classmethod & staticmethod 区别
- python classmethod,staticmethod实现
- python 的@classmethod &&@staticmethod
- 【python】classmethod 和staticmethod
- python @staticmethod @classmethod 区别
- Python @staticmethod@classmethod用法
- org.springframework.web.filter.DelegatingFilterProxy
- 6. ZigZag Conversion
- Ubuntu 16.04设置root用户登录图形界面
- [Leetcode][python]Partition List
- Linux CentOS7下安装Zookeeper-3.4.10服务(最新)
- python @,@staticmethod,@classmethod
- Java泛型详解
- C++中的explicit关键字
- 190. Reverse Bits
- 从零基础认识maven工程构建
- java不同安装包的安装方法(rpm,bin,tar)
- 一元多项式的加法器 C语言版 链表版 顺序表版
- 解决Atom 的 GitHub 和 Git 面板无法打开
- 算法设计与分析——使用dijkstra算法计算最短路径并且给出路径上的节点序列