最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

python类方法和普通方法区别

来源:动视网 责编:小采 时间:2020-11-27 14:06:23
文档

python类方法和普通方法区别

python类方法和普通方法区别:python类方法和普通方法区别下面用例子的方式,说明其区别。首先, 定义一个类,包括2个方法:class Apple(object): def get_apple(self, n): print "apple: %s,%s" % (self,n) @classmethod def get_clas
推荐度:
导读python类方法和普通方法区别:python类方法和普通方法区别下面用例子的方式,说明其区别。首先, 定义一个类,包括2个方法:class Apple(object): def get_apple(self, n): print "apple: %s,%s" % (self,n) @classmethod def get_clas

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类方法和普通方法区别:python类方法和普通方法区别下面用例子的方式,说明其区别。首先, 定义一个类,包括2个方法:class Apple(object): def get_apple(self, n): print "apple: %s,%s" % (self,n) @classmethod def get_clas
推荐度:
标签: 方法 区别 区分
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top