Python类中@property、@classmethod和静态方法的区别与使用场景详解

[id_[id_130633128]866980778]

Python类中@property、@classmethod和静态方法的区别与使用场景详解

class Student(object): 
    school='szu'
    @property
    def printmassage(self):
        print('aaaa')
s1=Student()
s1.printmassage    #aaaa

类方法是类对象所拥有的方法。它需要用修饰器@classmethod来标识自己为类方法。对于类方法来说,第一个参数必须是类对象,通常以 cls 作为第一个参数。这种类方法能够通过实例对象和类对象进行访问。

类方法一般有两个作用:一是访问类属性。二是修改类属性

'''
有问题没人解答吗?小编建立了一个 Python 学习交流的 QQ 群,群号是 778463939。
寻找有相同志向和兴趣的小伙伴,大家相互帮助。群里不但有较好的视频学习教程,还有 PDF 电子书。
'''
class Student(object):
    school='szu'
    @classmethod
    def printmassage(cls):
        print(cls.school)
    
s1=Student()
Student.printmassage()  #szu
s1.printmassage()       #szu

静态方法实际上是独立的,它依托于类而存在。然而,实际上它只是进行调取关系,只是在名义上被归类管理,实际上它就如同一个工具包,能够被类和实例所调用。并且,在静态方法中不能直接调用类方法,若要调用,必须加上类名字才行。

class Student(object):
    school='szu'
    @staticmethod
    def printmassage():
        print(Student.school)
    @staticmethod
    def func(x,y):
        print(x,y)
s1=Student()
Student.printmassage()  #szu
s1.printmassage()       #szu
Student.func(1,2)   #1 2
s1.func(1,2)            #1,2

你可能想看:
« 上一篇
下一篇 »

相关推荐

python爬虫教程PDF,Python爬虫书PDF

2026年09月02日

31阅读

外国教程python,python编程教学视频

2026年09月02日

25阅读

python简明教程沈洁元,python详细基础教程

2026年09月02日

21阅读

python库包教程,python 包

2026年09月02日

27阅读

python教程大全集,python教程600集

2026年09月02日

26阅读

python入门教程完整版,python零基础入门全套教程视频

2026年09月02日

22阅读