Lets dive straight into the basic concepts of OOPs (Object Oriented Programming) in python:
Classes and Objects
Just like standard class is the keyword for declaring classes. When defining a class in Python we use __init__
as the constructor method for the class and have to pass self as the first parameter so that when we declare Object of such class it bind the attributes that we pass as arguments.
Object variables vs class variables:
Object variables are only tied to the current object where as class variables are variables that shared among all objects or instances.
In the example above increment_salary
is a class variable which can be applied similarly to all the object via the method increment_salary()
Class Methods and Static Methods
Class methods can be used to change a class variable or also usually used as alternative constructors. We declare a classmethod by adding decorator @classmethod
to the top of function that we are adding to the class. For example we add functions change_increment_salary
and from_string
. Also when we declare a class method we also pass class as first argument, we cannot use class
as its reserved. but the first argument pass is just a class followed by other parameters.
Static methods on the other hand are just like regular methods but we dont pass any class or instance as argument, we only the parameters. We add a decorator @staticmethod
to the top of function to declare the method as static. The reason we add them to a class is that they have to have some kind of logical connection to the class. for example in our we add is_workday()
to check if the day is working day.