# Method Types In Python In python some methods receive as a parameter the ***self\*** keyword, others the ***cls\****,* and others just nothing ## Why? Let us first undertand the difference between class and instance `class` is a blueprint/template for creating objects - class is created using `class` keyword ```python3 class MyClass: pass ``` An object is created using the constructor of the class, That object is called an `Instance` of the class. ```python3 class Person: def greet(self): print('konnichiwa') # here naruto is an object and # naruto is an instance of the Person class naruto = Person() naruto.greet() # output: "konnichiwa" ``` > what is constructor in python? ```python3 def __init__(self): pass ``` > In Python the `__init__()` method is called the constructor and is always called when an object is created. Note: there are 2 types of constructors, default and parameterized previous example was of default constructor and this is an example of parameterized constructor ```python3 def __init__(self, data): self.left = None self.right = None self.data = data ``` # Now, let's talk about methods There are 3 types of methods - `Instance method` - `Class method` - `Static method` ```Python3 class MyClass: def method(self): return 'instance method', self @classmethod def classmethod(cls): return 'class method', cls @staticmethod def staticmethod(): return 'static method' ``` ## Instance Method The 1st method `Method` is the instance method, which is the most common method. It needs self parameter to access attributes and other methods of the same object. It can also access the class using `self.__class__` attribute. ## Class Method In the 2nd method classmethod, it is maked with @classmethod decorator to mark it as a classmethod. It has a `cls` parameter which points to the class instead of object instance. ## Static Method At the last method staticmethod, it is marked with @staticmethod decorator to mark it as a staticmethod. It cannot modify object instance state nor class, But it can have other parameters which is applicable for other 2 methods. # Let's see what happens if we run these ```Python3 if __name__ == '__main__': obj = MyClass() print(obj.method()) print(obj.classmethod()) print(obj.staticmethod()) ``` ``` Output: ('instance method', <__main__.MyClass object at 0x7f3cd59780d0>) ('class method', <class '__main__.MyClass'>) static method ``` We can call classmethod and staticmethod like this ```python3 print(MyClass.classmethod()) print(MyClass.staticmethod()) ``` > Output: > print(MyClass.classmethod()) print(MyClass.staticmethod()) So we can see instance method only needs object instance (for the self parameter) ###### tags: `python`