Python Tutorial
Python - Introduction Python - Syntax Python - Variable Python - Number Python - Casting Python - String Python - Operators Python - Conditions Python - Loops Python - List Python - Tuple Python - Set Python - Dictionary Python - Function Python - Module Python - Date & Time Python - Input Output Python - Error & Exception Python - File Handling
Python OOP
OOP - Introduction OOP - Class Members OOP - Constructor Destructor OOP - Data Hiding OOP - Inheritance OOP - Overriding OOP - Overloading

Python Class Members

A class is made up of its members (variables/property and functions/methods).

A Property/data member is a state.

A Method is an action.


Class and Instance Variables (Or attributes)

In Python, instance variables are variables whose value is assigned inside a constructor or method with self keyword.

Class variables are variables whose value is assigned in class.

Class variables doesn't require self statement.

You can access class variables inside class using className:



Defining Methods

Methods are class-specific functions. Individual actions that an object will be able to perform are defined within the class as methods.


Method with arguments

You can pass arguments to method, it is same as passing arguments to functions.


Python Class Method

The @classmethod decorator, is a builtin function decorator that is an expression that gets evaluated after your function is defined.

The result of that evaluation shadows your function definition.

A class method receives the class as implicit first argument, just like an instance method receives the instance.

  • A class method is a method which is bound to the class and not the object of the class.
  • They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance.
  • It can modify a class state that would apply across all the instances of the class. For example it can modify a class variable that will be applicable to all the instances.

A class method takes cls as first parameter.


Python Static Method

A static method is accessed without creating an object of a class.

  • A static method is also a method which is bound to the class and not the object of the class.
  • A static method can’t access or modify class state.
  • It is present in a class because it makes sense for the method to be present in class.

Class method vs Static Method

  • A class method takes cls as first parameter while a static method needs no specific parameters.
  • A class method can access or modify class state while a static method can’t access or modify it.
  • In general, static methods know nothing about class state. They are utility type methods that take some parameters and work upon those parameters. On the other hand class methods must have class as parameter.
  • We use @classmethod decorator in python to create a class method and we use @staticmethod decorator to create a static method in python.