![图片[1]-Python静态函数和普通方法的区别-uusu优素-乐高,模型,3d打印,编程](http://uusucn.zbbe.cn/wp-content/uploads/2024/01/5e8703373d3ac649.jpg)
Python静态函数和普通方法的区别
下面通过一个例子,讲解Python静态函数、普通方法、类方法的区别
#-*-coding:utf-8-*- #普通方法,类方法,静态方法的区别 __metaclass__=type classTst: name='tst' data='thisisdata' #普通方法 defnormalMethod(self,name): printself.data,name #类方法,可以访问类属性 @classmethod defclassMethod(cls,name): printcls.data,name #静态方法,不可以访问类属性 @staticmethod defstaticMethod(name): printname
三种方法都可以通过实例来调用,但是静态方法和类方法无法访问实例属性,所以更改了tst.data仅对普通方法起了作用
tst=Tst()
tst.data='thisisnew'
tst.normalMethod('name')
tst.staticMethod('name')
tst.classMethod('name')
#结果
thisisnewname
name
thisisdataname
区别
普通方法不能通过类名调用,但是静态方法和类方法是可以的
#error普通方法必须通过实例调用#
Tst.normalMethod('name')Tst.classMethod('name')
Tst.staticMethod('name')#结果thisisdataname
name
总结:
1、普通方法,可以通过self访问实例属性
defnormalMethod(self,data)
2、类方法,可以通过cls访问类属性
@classmethod defclassMethod(cls,data)
3、静态方法,不可以访问,通过传值的方式
@staticmethod defstaticMethod(data)原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END

















































暂无评论内容