Methods w/ Decorators

class Cls:
 
    def __init__(self):
        self.var = "instance" # shadows class variable `var`
 
    def instance_method(self):
        print(self.var)
    
    var = "class"
 
    @classmethod
    def class_method(cls):
        print(cls.var, cls().var, sep=", ")
 
    @staticmethod
    def static_method():
        print("static")
 
                        # prints
print(Cls().var)        # "instance"
Cls().instance_method() # "instance"
 
print(Cls.var)          # "class"
Cls().class_method()    # "class, instance"
 
Cls.static_method()     # "static"
Cls().static_method()   # "static"

Instance Method

There’s no decorator for instance method as, by default, a method in class is instance method

self is normally preferred convention to refer current instance

Class Method

decorator is @classmethod

cls is normally preferred convention to refer current class

In Line var = "class” , var is a class variable, so it can be accessed directly by class object

also cls is a callable, and here cls() is equivalent to Cls()

when it comes to first argument given to method i.e., self or cls, variable’s name doesn’t matter, it can be anything other than self or cls

Static Method

decorator is @staticmethod

this is pretty straight forward, they’re static

neither related to class nor instance, so no reference variable like self or cls

it can be called through class or instance