Object-Oriented Programming in Python
Here, I am going to explore Python object-oriented programming with examples but I will suggest if you are not familiar with the basics of python then please read my previous posts. Object-Oriented means everything is based on python class and object confused! let me explain, Class is a blueprint where you define logic and bind multiple functions in it. It is just like a newspaper where a couple of news is defined. Objects are real-time entities and these objects are used to access class functionality.
Any class can have multiple objects and every object has different property let us say we defined a class Laptop then objects can be Lenovo, hp, or dell. Leveno properties might be different from the hp object as the weight of the Lenovo laptop is different from the hp laptop.
Object-Oriented Programming in Python has Two main concepts 1st Class and 2nd Object. let us understand these concepts practically.
Class in Python
class math: def Area(self,pie,r): area=pie*r*r print("area of circle is =",area)
In the above example, you can see that I am defining a math class and binding a function area with this class so we can say that class is a unit that binds some functionality.
Object in python
obj=math() pie=3.14 r=float(input("please enter circle radius")) obj.Area(pie,r)
obj is the object name, you can give any name so first I am creating an object of class math then accessing its Area(..) function as Area(..) function is part of math class.
Basically, we do object-oriented programming in two steps.
1- Define a class with functionality.
2- Create an Object then access Class Functionality.
__init__() function in python
This function is used to create global variables in python and you can use these variables anywhere in the program. __init__ is a class constructor that executes auto when you create an object of the class. Let us take a quick demo.
class math: def __init__(self,pie): self.pie=pie # creating global variable pie def logic(self,r): area=self.pie*r*r # accessing global variable print("area=",area)
Accessing class functions using an Object, In the above code self is a pointer to the current object of class math and I am creating a global variable pie moreover I am using this global variable inside the logic function using self keyword.
obj=math(3.14) # passing 3.14 pie value inside class constructor. r=float(input("please enter radius value")) obj.Logic(r)
Thanks, Hope this will help and i will update more on OOP.