Expt 6 Theory
Expt 6 Theory
Roll no.:55
Div and Class: TY CSE B
Experiment Title: OOP in python
#### 1. **Classes**
- A class is a blueprint for creating objects. It defines a set of attributes
and methods that the objects created from the class will have.
- A class is defined using the `class` keyword followed by the class name
and a colon.
- Inside the class, you can define attributes (variables) and methods
(functions).
```python
class Car:
# Class attributes
wheels = 4
# Constructor method
def __init__(self, make, model):
# Instance attributes
self.make = make
self.model = model
# Method
def display_info(self):
print(f"Car make: {self.make}, model: {self.model}")
```
#### 2. **Objects**
- An object is an instance of a class. When a class is defined, no memory is
allocated until an object of that class is created.
- You can create an object by calling the class name with its required
arguments.
```python
# Creating an object of the Car class
my_car = Car("Toyota", "Corolla")
#### 3. **Methods**
- Methods are functions defined inside a class that describe the behaviors
of the objects created from the class.
- The first argument of any method in a class must be `self`, which refers
to the instance of the object calling the method. `self` allows you to
access the attributes and methods of the class within the method.
```python
class Calculator:
def add(self, a, b):
return a + b
# Calling methods
print(calc.add(5, 3)) # Outputs: 8
print(calc.subtract(5, 3)) # Outputs: 2
```
#### 4. **Destructor**
- A destructor is a special method called when an object is about to be
destroyed. In Python, the destructor is defined by the `__del__` method.
- The destructor method is called when an object is deleted, or when the
reference count of the object reaches zero.
class MyClass:
def __init__(self, name):
self.name = name
print(f"{self.name} is created")
def __del__(self):
print(f"{self.name} is destroyed")
# Creating an object
obj = MyClass("Object1")
```python
class MyClass:
def __init__(self, name):
self.name = name
print(f"{self.name} is created")
def __del__(self):
print(f"{self.name} is destroyed")
# Creating an object
obj = MyClass("Object1")
#### 1. **Inheritance**
- Inheritance is a feature of object-oriented programming where a new
class (child or derived class) is created from an existing class (parent or
base class).
- The child class inherits all the attributes and methods of the parent class
but can also have additional attributes or methods or override existing
ones.
- The main advantage of inheritance is code reuse and the creation of
hierarchical class structures.
def speak(self):
print(f"{self.name} makes a sound")
class Parrot(Bird):
def sound(self):
print("Parrot says 'Squawk'")
class Sparrow(Bird):
def sound(self):
print("Sparrow says 'Chirp'")
parrot = Parrot()
sparrow = Sparrow()