Home > Backend Development > Python Tutorial > How to define methods in python classes

How to define methods in python classes

(*-*)浩
Release: 2019-07-09 10:17:28
Original
8211 people have browsed it

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.

How to define methods in python classes

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))
Copy after login

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))
Copy after login

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__))
Copy after login

Static method: add decorator (staticmethod)

The definition code is as follows:

class Student(object):
    @staticmethod
    def func(name):
        print('my name is {}'.format(name))
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template