OOP in Python 4

Instance Methods

This is the basic type of method and mostly used this method in OOP. This method take first parameter self which points to an instance of class. It can also accept more than one parameters but first parameter should be self. This method modify the current object state by using self parameter self can access all the attributes of current object and also can modify. This method can also change the class state by using self.__class__ attribute. Example

class MyClass:
  def method(self):
  return 'instance method called'

myclass_obj = MyClass()

This code will print instance method called

Class Method

This is an other type of method in OOP Python this method is marked with a decorator @classmethod to flag it as a class method.

Instead of accepting self parameter, class method take a cls parameter that points to the class and not the object instance When this method is called and if there are some changes to attributes by this method it will modify the main class attributes not only the current object. It’s means this method changes the class state.


class MyClass:
    def classmethod(cls):
        return 'class method called'

So, this is the way how we can call a class method

Static Method

This is third type of method which is defined by using @staticmethod decorator to flag it as a static method.

This type of methods never take a self parameter nor a cls parameter (but we are free to pass other parameters to this function). Therefore a static method can neither modify object state nor class state. Static method are restricted in what data they can access. Example

class MyClass:
    def sMethod():
       return 'static method called'

This is how we can define a static method. We can call static method by using class name like MyClass.sMethod()

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s