栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 中 instance method @classmethod 和 @staticmethod的区别

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python 中 instance method @classmethod 和 @staticmethod的区别

python中对于类内部定义的方法,分为三种,实例方法(对象方法)、类方法、静态方法
实例方法在被调用时,首先是需要以 obj.fun的方式调用,在调用的时候会偷偷传进去一个self。在定义时,需要在参数列表里写self,操作的变量的生命周期也是与此对象生命周期一致,并不能操作类下的属性(如下面代码中的aa),实际表现是操作无效,cls.aa还会被视为self.aa,如__init__
类方法在被调用时,首先是需要以 class.fun的方式调用,在调用的时候会向fun偷偷传进去一个cls。
静态方法可以由类名或对象名进行调用

class A():
    aa=1    
    def __init__(cls,a):
        cls.aa=a
    @classmethod
    def detect1(cls):
        print(cls.aa)
    @staticmethod
    def detect2(cls):
        print(cls.aa)
    def detect3(self):
    	print(self.aa)
    def detect4(cls):
    	print(cls.aa)
    @classmethod
    def detect5(self):
    	print(self.aa)
    @classmethod
    def set_clsattr(cls,a):
        cls.aa=a
if __name__=='__main__':
    oa=A(a=10)
    print(oa.aa) #10
    print(A.aa)# 1
    oa.detect3() #10
    oa.detect4() #10
	#由上方5行代码可见。obj.fun调用时,会向fun偷偷传进一个self,即使形参是cls,传入的实参也是self
    A.detect1() #1
    A.set_clsattr(2)
    print(A.aa) #2
    A.detect1() #2
    A.detect5() #2
	#由上方5行代码可见。obj.fun调用时,会向fun偷偷传进一个self,即使形参是self,传入的实参也是cls
    A.detect2(A) #2 
    A.detect2(oa) #10
    oa.detect2(A) #2
    oa.detect2(oa)#10
    #由上方4行代码可见,调用静态方法时,不取决于谁调用,取决于传入什么参数
    A.detect3() #detect3() missing 1 required positional argument: 'self'
    #由上方1行代码可见,不能cls.fun调用实例方法
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1001407.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号