有关staticmethod classmethod
2015-08-25 07:27
288 查看
class Test: def __init__(self, id): self.id = id def printd(self): print self.id print('Arg in Method: ', self) @staticmethod def smethod(*arg): print('Arg in staticMethod: ', arg) @classmethod def cmetod(*arg): print("Arg in classMethod: ", arg) #classmethod 是和一个class相关的方法,可以通过类或类实例调用,并将该class对象(不是class的实例对象)隐式地 当作第一个参数传入 #staticmethod 基本上和一个全局函数差不多,不会隐式地传入任何参数 test = Test(1) test.printd() test2 = Test(2) test2.printd() test.cmetod() Test.cmetod() Test.smethod() test.smethod()
输出:
1
('Arg in Method: ', <method.Test instance at 0x00000000028D9208>)
2
('Arg in Method: ', <method.Test instance at 0x00000000028E3388>)
('Arg in classMethod: ', (<class method.Test at 0x00000000028D44C8>,))
('Arg in classMethod: ', (<class method.Test at 0x00000000028D44C8>,))
('Arg in staticMethod: ', ())
('Arg in staticMethod: ', ())
结论:
@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.
@staticmethod means: when this method is called, we don't pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method
does not use the instance).
相关文章推荐
- 良心干货|如何惊呆你的面试官
- java IO学习总结
- bzoj-2006 超级钢琴
- tomcat的简单安装及配置
- 异常笔记
- linux安装mysql后root无法登录
- IT人必备的设计网址(推荐时空隧道谷歌插件访问外网)
- Linux下Mysql的配置
- Linux安装MySQL的两种方法
- [Golang] 从零开始写Socket Server(4):将运行参数放入配置文件(XML/YAML)
- Spring MVC ParameterMethodNameResolver example
- Leetcode: Unique Binary Search Trees II
- Leecode_Single Number
- 正则表达式测试工具 regexbuddy
- 轻松python文本专题-单独处理字符串每个字符的方法汇总
- 轻松python文本专题-单独处理字符串每个字符的方法汇总
- CentOS6.5 升级 Python 2.7 版本
- Exactly-once Spark Streaming from Apache Kafka
- Exactly-once Spark Streaming from Apache Kafka
- C语言的标准库概述