Home > Article > Backend Development > How to define methods in python classes
The two most important members of a Python class are variables and methods. The class variables belong to the class itself and are used to define the state data contained in the class itself: while the instance variables belong to the objects of the class and are used to Define the state data contained in the object: methods are used to define the behavior or function implementation of the object of this class.
For the definition of methods in Python classes, we can summarize four types: Recommended learning: Python video tutorial)
1. Without self, cls parameters and without decorators (staticmethod, classmethod)
The definition code is as follows:
class Student(object): def func(name): print('my name is {}'.format(name))
2 , Normal method definition, with self parameter
The definition code is as follows:
class Student(object): def func(self, name): print('my name is {}'.format(name))
3. Class method: add decorator (classmethod)
The definition code is as follows:
class Student(object): @classmethod def func(cls, name): print('my name is {} from {}'.format(name, cls.__name__))
Static method: add decorator (staticmethod)
The definition code is as follows:
class Student(object): @staticmethod def func(name): print('my name is {}'.format(name))
More Python related technologies Article, please visit the Python Tutorial column to learn!
The above is the detailed content of How to define methods in python classes. For more information, please follow other related articles on the PHP Chinese website!