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教程 python编程 python使用问题 python类方法
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。
抱歉,评论功能暂时关闭!