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 '__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类方法和普通方法区别的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

Linux终端中查看Python版本时遇到权限问题的解决方法当你在Linux终端中尝试查看Python的版本时,输入python...

在使用Python的pandas库时,如何在两个结构不同的DataFrame之间进行整列复制是一个常见的问题。假设我们有两个Dat...

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

Uvicorn是如何持续监听HTTP请求的?Uvicorn是一个基于ASGI的轻量级Web服务器,其核心功能之一便是监听HTTP请求并进�...

在Python中,如何通过字符串动态创建对象并调用其方法?这是一个常见的编程需求,尤其在需要根据配置或运行...

本文讨论了诸如Numpy,Pandas,Matplotlib,Scikit-Learn,Tensorflow,Tensorflow,Django,Blask和请求等流行的Python库,并详细介绍了它们在科学计算,数据分析,可视化,机器学习,网络开发和H中的用途

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...
