当前位置: 首页 > Python编程 > Python编程实战技能 > Python编程学习教程 > python类方法和普通方法区别

python类方法和普通方法区别

发布时间:2020年11月17日 03:57:21 来源:环球青藤 点击量:590

【摘要】python类方法和普通方法区别下面用例子的方式,说明其区别。首先, 定义一个类,包括2个方法: class Apple(object): de

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", pne 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类方法和普通方法区别的详细内容希望对大家有所帮助,更多有关python教程请关注环球青藤其它相关文章!

分享到: 编辑:wangmin

就业培训申请领取
您的姓名
您的电话
意向课程
点击领取

环球青藤

官方QQ

扫描上方二维码或点击一键加群,免费领取大礼包,加群暗号:青藤。 一键加群

绑定手机号

应《中华人民共和国网络安全法》加强实名认证机制要求,同时为更加全面的体验产品服务,烦请您绑定手机号.

预约成功

本直播为付费学员的直播课节

请您购买课程后再预约

环球青藤移动课堂APP 直播、听课。职达未来!

安卓版

下载

iPhone版

下载
环球青藤官方微信服务平台

刷题看课 APP下载

免费直播 一键购课

代报名等人工服务

课程咨询 学员服务 公众号

扫描关注微信公众号

APP

扫描下载APP

返回顶部