您的位置:首页 > 编程语言 > Python开发

python 普通方法、静态方法和类方法有什么区别?

2017-04-30 11:40 549 查看
下面用例子的方式,说明其区别。

首先, 定义一个类,包括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.html

http://www.cnblogs.com/chenzehe/archive/2010/09/01/1814639.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐