python中staticmethod classmethod及普通函数的区别
来源:互联网 发布:php 循环倒计时 编辑:程序博客网 时间:2024/05/16 12:08
staticmethod 基本上和一个全局函数差不多,只不过可以通过类或类的实例对象(python里光说对象总是容易产生混淆, 因为什么都是对象,包括类,而实际上类实例对象才是对应静态语言中所谓对象的东西)来调用而已, 不会隐式地传入任何参数。这个和静态语言中的静态方法比较像。
classmethod 是和一个class相关的方法,可以通过类或类实例调用,并将该class对象(不是class的实例对象)隐式地 当作第一个参数传入。就这种方法可能会比较奇怪一点,不过只要你搞清楚了python里class也是个真实地 存在于内存中的对象,而不是静态语言中只存在于编译期间的类型。
正常的方法就是和一个类的实例对象相关的方法,通过类实例对象进行调用,并将该实例对象隐式地作为第一 个参数传入,这个也和其它语言比较像。
可如下示例:
- #!/usr/bin/python
- #coding:utf-8
- #author: gavingeng
- #date: 2011-12-03 10:50:01
- class Person:
- def __init__(self):
- print "init"
- @staticmethod
- def sayHello(hello):
- if not hello:
- hello='hello'
- print "i will sya %s" %hello
- @classmethod
- def introduce(clazz,hello):
- clazz.sayHello(hello)
- print "from introduce method"
- def hello(self,hello):
- self.sayHello(hello)
- print "from hello method"
- def main():
- Person.sayHello("haha")
- Person.introduce("hello world!")
- #Person.hello("self.hello") #TypeError: unbound method hello() must be called with Person instance as first argument (got str instance instead)
- print "*" * 20
- p = Person()
- p.sayHello("haha")
- p.introduce("hello world!")
- p.hello("self.hello")
- if __name__=='__main__':
- main()
output:
- i will sya haha
- i will sya hello world!
- from introduce method
- ********************
- init
- i will sya haha
- i will sya hello world!
- from introduce method
- i will sya self.hello
- from hello method
阅读全文
0 0
- python中staticmethod classmethod及普通函数的区别
- python中staticmethod classmethod及普通函数的区别
- python中staticmethod classmethod及普通函数的区别
- Python中classmethod, staticmethod和普通method的区别
- python 中 @classmethod 、staticmethod 和 普通方法 的区别
- python中 classmethod、staticmethod和普通方法的区别
- python中staticmethod和classmethod的区别
- python中classmethod和staticmethod的区别
- python中staticmethod和classmethod的区别
- python中@classmethod @staticmethod区别
- Python: classmethod & staticmethod 区别
- Python: classmethod & staticmethod 区别
- Python: classmethod & staticmethod 区别
- python @staticmethod @classmethod 区别
- python中@staticmethod 、@classmethod 与一般方法的区别
- python中@classmethod与@staticmethod的区别和用法
- Python中@staticmethod和@classmethod的区别和用法
- python中classmethod与staticmethod的差异及应用
- 专题一关键字的剖析----3.if,switch,do,while,for分析
- 指针(一)
- 反射获取其他apk中类的变量和方法
- H264码流保存为YUV数据 通过H264Visa软件转换
- python写一个录音小程序
- python中staticmethod classmethod及普通函数的区别
- 机房收费系统之九(导出Excel)
- ORACLE 多表连接与子查询
- MySQL行级锁、表级锁、页级锁详细介绍
- AndroidStudio ImageView全屏显示
- Codeforces 490E Restoring Increasing Sequence【二分+模拟】细节题
- 关于Android的PopupWindon
- 初学数据结构---查找代码之静态查找
- android 仿Boss直聘消息界面