码迷,mamicode.com
首页 > 编程语言 > 详细

Python类的静态属性、类方法、静态方法

时间:2018-05-09 19:36:18      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:color   pre   nbsp   sage   类方法   就是   print   object   method   

1、静态属性。@property。作用就是把类的函数属性,封装成类似数据属性。

class Student(object): 
    school=szu

    @property
    def printmassage(self):
        print(aaaa)

s1=Student()
s1.printmassage    #aaaa

2、类方法:是类对象所拥有的方法,需要用修饰器@classmethod来标识其为类方法,对于类方法,第一个参数必须是类对象,一般以cls作为第一个参数,能够通过实例对象和类对象去访问。

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

class Student(object):
    school=szu

    @classmethod
    def printmassage(cls):
        print(cls.school)
    

s1=Student()
Student.printmassage()  #szu
s1.printmassage()       #szu

 

 3、静态方法:静态方法实际上是独立的,依靠在类中,但实际是只是调取关系。只是名义上归类管理,实际上就是一个工具包,可以供类和实例调用。静态方法里不能直接调用类方法,要调用必须加上类名字去调用。

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类的静态属性、类方法、静态方法

标签:color   pre   nbsp   sage   类方法   就是   print   object   method   

原文地址:https://www.cnblogs.com/linshuhui/p/9015798.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!