-
Overview
-
How many types of methods in Python
Generally, there are three types of methods in Python:
- Instance Methods
- Class Methods
- Static Methods
Knowing the differences isn’t always required to code basic Python scripts, but once you advance into OOP, the differences can make a big change.
-
Instance Methods
The regular instance method takes the parameter
self
which points to an instance of Class when the method id called. -
Class Methods
The class methods take a
cls
parameter that points to the class - not the object instance - when the method is called.They can call other static methods.
That means it can’t modify object instance state;
-
Static Methods
The static methods takes neither a
self
nor acls
parameter (but of course it’s free to accept an arbitrary number of other parameters).That means a static method can neither modify object state or class state.
Static methods are restricted in what data they can access - and they’re primarily a way to namespace your methods.
-
When to Use Each Method Type
-
References
文章评论