python 普通方法、静态方法和类方法有什么区别?
2017-04-30 11:40
549 查看
下面用例子的方式,说明其区别。
首先, 定义一个类,包括3个方法:
输出结果
再看绑定关系:
类的普通方法,只能用类的实例去使用。如果用类调用普通方法,出现如下错误:
再看绑定关系:
输出结果,用实例和用类调用是一样的。
再看绑定关系
输出结果
http://www.cnblogs.com/chenzehe/archive/2010/09/01/1814639.html
首先, 定义一个类,包括3个方法:
class Apple(object): def get_apple(self, n): print "apple: %s,%s" % (self,n) @classmethod def get_class_apple(cls, n): print "apple: %s,%s" % (cls,n) @staticmethod def get_static_apple(n): print "apple: %s" % n
类的普通方法
类的普通方法,需要类的实例调用。a = Apple() a.get_apple(2)
输出结果
apple: <__main__.Apple object at 0x7fa3a9202ed0>,2
再看绑定关系:
print (a.get_apple) <bound method Apple.get_apple of <__main__.Apple object at 0x7fa3a9202ed0>>
类的普通方法,只能用类的实例去使用。如果用类调用普通方法,出现如下错误:
Apple.get_apple(2) Traceback (most recent call last): File "static.py", line 22, in <module> Apple.get_apple(2) TypeError: unbound method get_apple() must be called with Apple instance as first argument (got int instance instead)
类方法
类方法,表示方法绑定到类。a.get_class_apple(3) Apple.get_class_apple(3) apple: <class '__main__.Apple'>,3 apple: <class '__main__.Apple'>,3
再看绑定关系:
print (a.get_class_apple) print (Apple.get_class_apple)
输出结果,用实例和用类调用是一样的。
<bound method type.get_class_apple of <class '__main__.Apple'>> <bound method type.get_class_apple of <class '__main__.Apple'>>
静态方法
静态方法,实际上就是一个方法。a.get_static_apple(4) Apple.get_static_apple(4) apple: 4 apple: 4
再看绑定关系
print (a.get_static_apple) print (Apple.get_static_apple)
输出结果
<function get_static_apple at 0x7fa3a92078c0> <function get_static_apple at 0x7fa3a92078c0>
参考
https://taizilongxu.gitbooks.io/stackoverflow-about-python/content/14/README.htmlhttp://www.cnblogs.com/chenzehe/archive/2010/09/01/1814639.html
相关文章推荐
- synchronized修饰静态方法和普通方法有什么区别
- 虚方法的重写与普通方法的隐藏的区别;抽象方法和虚方法有什么区别?
- python类的静态方法和类方法区别
- Python中普通方法、staticmethod、classmethod的区别
- 记录一个 关于 python 普通方法,静态方法和类方法 的介绍。@classmethod @staticmethod
- 构造方法和普通方法有什么区别
- Python中字符串的split()方法和split(‘ ’)有什么区别
- Python:类属性,实例属性,私有属性与静态方法,类方法,实例方法 属性分为实例属性与类属性 方法分为普通方法,类方法,静态方法 一:属性: 尽量把需要用户传入的属性作为实例属性,而
- python中 classmethod、staticmethod和普通方法的区别
- static 静态方法 有什么优缺点 PHP中静态方法(static)与非静态方法的使用及区别
- python中静态方法和类方法的区别
- Java中的构造方法与普通方法的区别? 什么情况下用构造方法什么情况下用普通的方法
- static 静态方法 有什么优缺点 PHP中静态方法(static)与非静态方法的使用及区别
- static 静态方法 有什么优缺点 PHP中静态方法(static)与非静态方法的使用及区别
- python中类方法、静态方法和普通方法
- python 类中 普通方法,类方法,静态方法的区别?
- python类的实例方法\静态方法\类方法区别解析(附代码)
- Python的静态方法和类方法有什么区别
- php静态方法与非静态方法在性能上有什么区别?
- 构造方法和普通方法有什么区别呢,我很疑惑?