python的 普通方法、静态方法和类方法有什么区别?

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

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

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)

        @staticmethod
        def get_static_apple(n):
                print "apple: %s" % n
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

类的普通方法

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

a = Apple()
a.get_apple(2)
   
   
  • 1
  • 2

输出结果

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

再看绑定关系:

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
  • 5
  • 6

类方法

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

a.get_class_apple(3)
Apple.get_class_apple(3)

apple: <class '__main__.Apple'>,3
apple: <class '__main__.Apple'>,3
   
   
  • 1
  • 2
  • 3
  • 4
  • 5

再看绑定关系:

print (a.get_class_apple)
print (Apple.get_class_apple)
   
   
  • 1
  • 2

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

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

静态方法

静态方法,实际上就是一个方法。

a.get_static_apple(4)
Apple.get_static_apple(4)

apple: 4
apple: 4
   
   
  • 1
  • 2
  • 3
  • 4
  • 5

再看绑定关系

print (a.get_static_apple)
print (Apple.get_static_apple)
   
   
  • 1
  • 2

输出结果

<function get_static_apple at 0x7fa3a92078c0>
<function get_static_apple at 0x7fa3a92078c0>
   
   
  • 1
  • 2

参考

https://taizilongxu.gitbooks.io/stackoverflow-about-python/content/14/README.html

http://www.cnblogs.com/chenzehe/archive/2010/09/01/1814639.html

        <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/markdown_views-ea0013b516.css">
            </div>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值