Static attributes, class methods, static methods of Python classes

1. Static properties. @property. The function is to encapsulate the function attributes of the class into similar data attributes.

class Student(object): 
    school = ' szu '

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

s1=Student()
s1.printmassage    #aaaa

2. Class method: It is a method owned by a class object. It needs to be identified as a class method with a decorator @classmethod. For a class method, the first parameter must be a class object, which is generally used clsas the first parameter, which can be passed through the instance object and class object to access.

Class methods generally have two functions: one is to access class attributes. The second is to modify the class attributes

class Student(object):
    school = ' szu '

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

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

 

 3. Static method: Static method is actually independent and depends on the class, but it is actually just a call relationship. It is only nominally classified and managed, but it is actually a toolkit that can be invoked by classes and instances. The class method cannot be called directly in the static method, and the class name must be added to call it.

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   

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326376764&siteId=291194637