Python, a popular programming language, offers a powerful feature called object-oriented programming (OOP).
This approach allows developers to organize their code in a way that makes it easier to understand and reuse.
Central to OOP in Python are classes, which act as blueprints for creating objects with shared characteristics and behaviors.
Classes
They are abstract and blueprint only. For example, Let's imagine a map of your house before you construct it is class.
One class can have many objects like we can make multiple houses with the help of the same map.
class Classname: #your variables and functions
Objects
When the house is constructed from it then it is considered an object which exists and is real.
Similarly, various features of house such as color, furniture, number of rooms, etc are also objects.
object_name = Classname()
Some examples to create classes and objects :
#creating class
class Number:
def sum(self):
return self.a + self.b
obj = Number()
obj.a = 10
obj.b = 10
s = obj.sum()#calling sum() with
print(s) # Object = 20
Creating a class with constructor(__init__())
class Map:
#instance method because it is bound to instance of class
category = 'house_category'
def __init__(self, color, num_rooms, area):
#declaring instance variable
self.color = color
self.num_rooms = num_rooms
self.area = area
# Creating different objects for the House class
house1 = Map("Green", 10, 2500)#object1
house2 = Map("Orange", 2, 1000)#object3
print(house1.color) # Output = Green
print(house2.num_rooms) # Output = 2
__init__() constructor
__init__
method is the constructor in Python which is automatically called at the time of object creation.__init__
is the instance method because it is bound to the instance of the class.Various variable inside this method is instance variable because it is associated with the object(
self
)category variable or attributes outside init consctuctor is class variable.
Self keyword
self
parameter is automatically passed as the first argument whenever the method is called.By convention, it is named
self
, although you can technically use any valid variable name in its place.self
is the object in python.self
parameter allows you to access and manipulate the instance's attributes and call other instance methods within the class. For instance, self.attribute_name or self.function_name()