python类和类方法的区别_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>,2

再看绑定关系:print (a.get_apple)

>

类的普通方法,只能用类的实例去使用。如果用类调用普通方法,出现如下错误:Apple.get_apple(2)

Traceback (most recent call last): File "static.py", line 22, in 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: ,3

apple: ,3

再看绑定关系:print (a.get_class_apple) print (Apple.get_class_apple)

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

相关推荐:《Python教程》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值