python类方法和普通方法区别


本文摘自php中文网,作者藏色散人,侵删。

python类方法和普通方法区别

下面用例子的方式,说明其区别。

首先, 定义一个类,包括2个方法:

1

2

3

4

5

6

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)

类的普通方法

类的普通方法,需要类的实例调用。

1

2

a = Apple()

a.get_apple(2)

输出结果

1

apple: <__main__.Apple object at 0x7fa3a9202ed0>,2

再看绑定关系:

1

2

print (a.get_apple)

<bound method Apple.get_apple of <__main__.Apple object at 0x7fa3a9202ed0>>

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

1

2

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)

类方法

类方法,表示方法绑定到类。

1

2

3

4

a.get_class_apple(3)

Apple.get_class_apple(3)

apple: <class '__main__.Apple'>,3

apple: <class '__main__.Apple'>,3

再看绑定关系:

1

print (a.get_class_apple) print (Apple.get_class_apple)

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

1

<bound method type.get_class_apple of <class '__main__.Apple'>> <bound method type.get_class_apple of <class '__main__.Apple'>>

相关推荐:《Python教程》

以上就是python类方法和普通方法区别的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

tensorflow 使用flags定义命令行参数的方法

Python里的str是什么意思

return语句是什么?return语句起到什么样的作用?

Python能画3d图吗

Python中常见字符串方法推荐

Python不支持的数据类型是什么

Python找工作难吗

Python怎么安装词云wordcloud

Python file seek() 方法是什么?怎么理解并使用它?

Python源代码被解释器转换后的格式为什么

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...