Instance Methods in Python
- The most common type of methods in Python classes, instance methods are called as they are because they can and should access unique data of each instance.
- Instanec methods must have self as a parameter
- Of course, instance methods do not require decorators; any method you create will automatically be created as an instance method, unless you specify a method type to Python
Static Methods in Python
- Static methods do not require accessing any class-specific data, though they are still related to a class in some way
- No need for self parameter
- No need to instantiate an instance to use this method; simply call it
- @staticmethod decorator tells Python that this method is a static method
- Great for utility functions that need to perform a task in isolation, that don't and can't access class data; they should only be working with data passed in as arguments
class ExampleClass:
greeting = ""
def __init__(self, name):
greeting = "Hello " + name
@staticmethod
def function_example():
print('Tis a static method')
Class Methods in Python
- Class methods cannot access specific instance data, but they do know about thier class -- they can access class variables and other static methods
- Also do not need self parameter, but requires cls parameter
- Class methods use the @classmethod decorator
class ExampleClass:
greeting = ""
def __init__(self, name):
greeting = "Hello " + name
@classmethod
def function_example(cls):
print("Tis a class method")
cls.other_static_function()
Referenced article