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类方法和普通方法区别的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

实例详解Python实现简单网页图片抓取

实例详解Python使用回溯法子集树模板获取最长公共子序列问题

django遇到的地雷,大家要注意

Python的random怎么用

Python和scratch如何选择?

Python 是什么?

Python中的strip是什么意思

django中怎么更改默认数据库为mysql(详细过程)

Python实现简单文本字符串处理的方法

int在Python中是什么意思

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




打赏

取消

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

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

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

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

评论

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