知行编程网知行编程网  2022-08-18 20:00 知行编程网 隐藏边栏  11 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于python静态方法和类方法的区别有哪些的相关知识,包括python中类方法,以及python什么时候用静态方法这些编程知识,希望对大家有参考作用。

python静态方法和类方法有什么区别


区别:

静态方法装饰器下定义的方法属于函数(function);

类方法装饰器下定义的方法属于方法(method);

静态方法无需传入任何参数;

类方法传入的第一个参数必须是class本身cls;

一旦调用了静态方法和类方法,就确定了内存地址。从类调用与从实例化对象调用的结果完全相同。

直接上代码:

#  coding:utf-8
class Apple:
    def fun1(self):
        return 'normal'
    @staticmethod
    def fun2():
        return 'staticmethod'
    @classmethod
    def fun3(cls):
        return 'classmethod'
print Apple.fun1
print Apple.fun2
print Apple.fun3
print "-"*80
apple = Apple()
print apple.fun1
print apple.fun2
print apple.fun3
print "-"*80
apple1 = Apple()
print apple1.fun1
print apple1.fun2
print apple1.fun3

运行结果:

<unbound method Apple.fun1>
<function fun2 at 0x00000000022FC4A8>
<bound method classobj.fun3 of <class __main__.Apple at 0x0000000001E7C768>>
--------------------------------------------------------------------------------
<bound method Apple.fun1 of <__main__.Apple instance at 0x00000000022FAE08>>
<function fun2 at 0x00000000022FC4A8>
<bound method classobj.fun3 of <class __main__.Apple at 0x0000000001E7C768>>
--------------------------------------------------------------------------------
<bound method Apple.fun1 of <__main__.Apple instance at 0x00000000022FAE48>>
<function fun2 at 0x00000000022FC4A8>
<bound method classobj.fun3 of <class __main__.Apple at 0x0000000001E7C768>>

普通方法传入的第一个参数必须是self(当然self也可以省略,官方要求尽量使用self),self指的是实例对象本身;静态方法不需要传递参数;

类方法传入的第一个参数必须是class,是指类本身。

对比结果1,5,9行

通过类调用fun1时,是一个未绑定的方法,但是实例化了apple和apple1后,属于绑定的方法,而实例化的apple和apple1由于属于不同的实例对象,内存地址不同。

对比结果2,6,10行

类调用和实例化对象调用的静态方法fun2没有区别,都指向同一个内存地址。可以简单理解为静态方法与类或实例无关。一旦被调用,它的内存地址就被确定了。

对比结果3,7,11行

类调用的类方法fun3和实例化对象调用的类方法fun3没有区别,都指向同一个内存地址。为什么?因为实例化的对象apple和apple1调用了类方法fun3,传入的第一个参数就是类本身Apple,即apple.fun3 = apple1.fun3 = Apple.fun3。

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享