首页 / PYTHON / python类方法和普通方法区别
python类方法和普通方法区别
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python类方法和普通方法区别,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1293字,纯文字阅读大概需要2分钟。
内容图文
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 '__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'>>
相关推荐:《Python教程》
以上就是python类方法和普通方法区别的详细内容,更多请关注Gxl网其它相关文章!
内容总结
以上是互联网集市为您收集整理的python类方法和普通方法区别全部内容,希望文章能够帮你解决python类方法和普通方法区别所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。