The static method is defined by @staticmethod, but the properties in the class and instance are not accessible in the static method, but the static method requires the class to invoke the
#-*-Coding:utf-8-*-__author__ = "MuT6 Sch01ar" class Person (object): def __init__ (self,name): self.name = name @staticmethod def Eat (Self,food): print ("%s is eating%s"% (Self.name,food)) if __name__ = = ' __main__ ': p = person (' John ') p.eat (' meat ')
Run, error
The parameters of the Eat method are removed and printed directly and can be called directly
#-*-Coding:utf-8-*-__author__ = "MuT6 Sch01ar" class Person (object): def __init__ (self,name): self.name = name @staticmethod def Eat (): print ("John is eating") if __name__ = = ' __main__ ': p = person (' john ') P.eat ()
Run results
If you want to pass parameters to eat (), you can pass the instantiated person into
#-*-Coding:utf-8-*-__author__ = "MuT6 Sch01ar" class Person (object): def __init__ (self,name): self.name = name @staticmethod def Eat (self): print ("%s was eating"%self.name) if __name__ = = ' __main__ ': p = person ( ' John ') p.eat (p)
Run results
Class methods are defined by @classmethod.
Class methods can access only class variables and cannot access instance variables
#-*-Coding:utf-8-*-__author__ = "MuT6 Sch01ar" class Person (object): name = ' Jack ' def __init__ (self,name):
self.name = name @classmethod def Eat (self): print ("%s is eating"%self.name) if __name__ = = ' __main__ ': p = person (' John ') p.eat ()
Run results
The instance variable was passed to John, but Jack was the one who printed it.
Because class methods cannot access instance variables, class methods access class variables in the class
Defining attribute methods with @property
To change a method in a class to a static property
#-*-Coding:utf-8-*-__author__ = "MuT6 Sch01ar" class Person (object): def __init__ (self,name): self.name = Name @property def Eat (self): print ("%s was eating"%self.name) if __name__ = = ' __main__ ': p = person (' John ') P.eat
Invoke the property method by invoking the property's method
If you want to pass arguments to attribute methods, use setter
Python Class (vi)-static method, class method, property method