python类方法和普通方法区别

藏色散人
发布: 2019-07-03 09:45:03
原创
3806 人浏览过

python类方法和普通方法区别

python类方法和普通方法区别

下面用例子的方式,说明其区别。

首先, 定义一个类,包括2个方法:

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)
登录后复制

类的普通方法

类的普通方法,需要类的实例调用。

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 &#39;__main__.Apple&#39;>,3
apple: <class &#39;__main__.Apple&#39;>,3
登录后复制

再看绑定关系:

print (a.get_class_apple) print (Apple.get_class_apple)
登录后复制

输出结果,用实例和用类调用是一样的。

<bound method type.get_class_apple of <class &#39;__main__.Apple&#39;>> <bound method type.get_class_apple of <class &#39;__main__.Apple&#39;>>
登录后复制

相关推荐:《Python教程

以上是python类方法和普通方法区别的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!