1. What is OOPS ( Object-Oriented Programming )?
2. Class in Python
A class is a blueprint or template used to create objects. It defines properties (variables) and methods (functions) that describe an object. For example, a “Car” class can have properties like color and speed, and methods like start and stop. Classes help reduce code repetition and improve structure. In Python, we create a class using the class keyword.
Example :
brand = "Toyota"
color = "Red"
my_car = Car()
print(my_car.brand)
3. Object in Python
An object is an instance of a class. It represents a real thing created using the class blueprint. When a class is defined, no memory is used until an object is created. Objects allow us to access class variables and methods. Multiple objects can be created from the same class, each having different values.
Example:
model = "Samsung"
phone1 = Mobile()
print(phone1.model)
4. Constructor (__init__ Method)
A constructor is a special method that runs automatically when an object is created. In Python, it is called __init__. It is used to initialize object data. Constructors make classes more dynamic because values can be passed while creating objects. This helps store different data for each object.
Example:
class Person:
def __init__(self, name, age):
self.name = name&
self.age = age
p1 = Person("Kamal", 22)
print(p1.name, p1.age)
5. Inheritance
Inheritance allows one class to use properties and methods of another class. The class that inherits is called the child class, and the class being inherited is the parent class. Inheritance helps reduce code duplication and improves reusability. It is useful when classes have a common relationship.
Example:
Post a Comment
If you have any doubts, please tell me know