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)
以上内容为大家介绍了Python静态函数和普通方法的区别,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

猜你喜欢LIKE
相关推荐HOT
更多>>
为什么Python爬虫使用MongoDB?
想必大家都知道,在从事网络爬虫工作之前,我们需要掌握很多知识,除了基本的爬虫原理之外,我们还需要学习框架、数据库等,其中就包含MongoDB...详情>>
2023-11-07 23:02:10
python如何进行类型转换的
python提供了将变量或值从一种类型转换成另一种类型的内置函数。1、int:将符合数学格式数字型字符串转换成整数。>>>int('123')1232、s...详情>>
2023-11-07 18:51:20
python怎么生成随机数
以下实例演示了python如何生成一个随机数:#生成0~9之间的随机数#导入random(随机数)模块importrandomprint(random.randint(0,9))执行以上代码...详情>>
2023-11-07 17:09:17
python如何删除空格
python中的字符串方法提供了如下常用的方法来删除空白:strip():删除字符串前后的空白。lstrip():删除字符串前面(左边)的空白。rstrip():删...详情>>
2023-11-07 14:57:44热门推荐
技术干货






