首页 >后端开发 >Python教程 > 正文

python类方法和普通方法区别

原创2019-07-03 09:45:0302058

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中文网其它相关文章!

php中文网最新课程二维码

声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理

  • 相关标签:python类方法
  • 相关文章

    相关视频


    网友评论

    文明上网理性发言,请遵守 新闻评论服务协议

    我要评论
  • 专题推荐

    推荐视频教程
  • Python进阶视频教程Python进阶视频教程
  • python编程入门系列图文教程python编程入门系列图文教程
  • 零基础入门Python项目实战零基础入门Python项目实战
  • Python+人工智能全栈工程师(Linux基础篇)Python+人工智能全栈工程师(Linux基础篇)
  • 视频教程分类