0% found this document useful (0 votes)
3 views12 pages

PF-Unit 1 - Basics - Part B - Introduction To OOP

Uploaded by

punyagarg03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views12 pages

PF-Unit 1 - Basics - Part B - Introduction To OOP

Uploaded by

punyagarg03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a way of thinking about and organizing your code that
makes it easier to build, understand, and manage. It revolves around two main ideas: classes and
objects.

What are Classes and Objects?

1. Objects: Think of objects as real-world things. For example, a car, a dog, or a book can all be
considered objects. In programming, objects are used to represent these real-world things, and
they have two main parts:
- Attributes (or properties): These are the characteristics of the object. For instance, a dog has
attributes like `name`, `age`, and `breed`.
- Methods (or functions): These are the actions the object can perform. For instance, a dog can
`bark()` or `sit()`.

2. Classes: A class is like a blueprint or a template for creating objects. Just like a blueprint of a
house defines what a house looks like but isn’t the house itself, a class defines the structure and
behavior of the objects that can be created from it.

Why Use Classes and Objects?


Using classes and objects helps organize your code in a way that is similar to how things work in
the real world. It allows you to:
 Model real-world entities: You can create digital representations of things you encounter
in real life.
 Reuse code: Once a class is defined, you can create multiple objects (instances) from it
without writing the same code again.
 Manage complexity: Large programs become easier to manage when broken down into
objects that interact with each other.

How to Create a Class in Python


Creating a class in Python involves defining it using the `class` keyword followed by the class
name:

```python
class Dog:
# This is a class attribute, shared by all instances of Dog
species = "Canine"

# The __init__ method is the constructor method


def __init__(self, name, age):
# These are instance attributes, unique to each instance
self.name = name
self.age = age

# A method is a function that belongs to a class


def bark(self):
print(f"{self.name} says Woof!")

# Creating an object (instance) of the Dog class


my_dog = Dog("Buddy", 4)

# Accessing attributes and methods of the object


print(my_dog.name) # Output: Buddy
print(my_dog.age) # Output: 4
my_dog.bark() # Output: Buddy says Woof!
```

Breaking Down the Above Code:


1. Defining the Class: `class Dog:` starts the definition of the class named `Dog`.
2. Class Attribute: `species = "Canine"` is an attribute shared by all instances of the class. All
dogs are "Canine".
3. Constructor Method (`__init__`): The `__init__` method is a special function called when you
create a new object (instance) from the class. It initializes the object’s attributes.
- `self`: Refers to the instance being created. It is used to access attributes and methods of the
class within its definition.
4. Instance Attributes: `self.name` and `self.age` are instance attributes, meaning each dog object
will have its own name and age.
5. Methods: `bark(self)` is a method belonging to the class, allowing each dog to "bark."

Creating Objects from a Class


To create an object (or an instance) of a class, you use the class name followed by parentheses:

```python
# Creating multiple objects
dog1 = Dog("Buddy", 4)
dog2 = Dog("Lucy", 3)

print(dog1.name) # Output: Buddy


print(dog2.name) # Output: Lucy
```

Each object `dog1` and `dog2` is a separate instance of the `Dog` class, each with its own `name`
and `age`.
Key Concepts in Simple Terms:

1. Encapsulation: Think of it like a capsule that holds everything an object needs—its data
(attributes) and the actions it can perform (methods). This keeps everything organized and
prevents outside interference.

2. Inheritance: Imagine a class as a family tree. A child class can inherit traits (attributes and
methods) from a parent class. This allows the child class to reuse the parent’s code, and also to
add or change things.
- For example, if you have a `Vehicle` class, you can create a `Car` class that inherits from
`Vehicle` but adds more specific details like `number_of_doors`.

3. Polymorphism: This allows different objects to be treated the same way even if they are of
different classes. For example, both a `Dog` and a `Cat` can have a `speak()` method, and you
can call `speak()` without needing to know exactly what kind of animal it is.

Visualizing with Real-World Examples:


o Class as a Blueprint: Imagine a cookie cutter (class) and the cookies (objects) made
from it. The cutter defines the shape (structure) and type (attributes) of the cookie but is
not itself a cookie.

o Encapsulation: Think of a TV remote with buttons (methods) you press to perform


actions. You don't need to know how it works internally; you just use the interface
provided.

o Inheritance: A `Smartphone` class can inherit from a general `Phone` class. All phones
have calling and texting capabilities, but smartphones add internet browsing and apps.

o Polymorphism: A `Shape` class could have different subclasses like `Circle`, `Square`,
and `Triangle`, each with a `draw()` method. Polymorphism allows you to call `draw()`
on any shape without worrying about the specific details of that shape.
Important Questions and Answers:
1. What is the difference between a class and an object?
A class is a blueprint or template for creating objects. An object is an instance of a class, which
means it's a specific example of that class with actual values and data.

2. What does the `__init__` method do?


The `__init__` method initializes a new object’s attributes when it is created. It sets up the
object with the required initial data.

3. What does the `self` keyword mean?


`self` refers to the instance of the class. It is used within the class methods to access instance
attributes and other methods.

4. Why use classes in programming?


Classes help to organize code into reusable blueprints that model real-world or logical
concepts, making the code easier to manage, understand, and extend.

5. Can a class have multiple objects?


Yes, you can create multiple objects from a single class, each with its own unique set of
attributes.

The Constructor Method

The `__init__` Method


The constructor method `__init__` is called automatically when an object is created. It initializes
the object's attributes.

Example:
```python
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year

def display_info(self):
return f"{self.year} {self.make} {self.model}"

car1 = Car("Toyota", "Corolla", 2020)


print(car1.display_info()) # Output: 2020 Toyota Corolla
```

Important Points:
 The constructor method can take arguments to initialize object attributes.
 `self` is always the first parameter.

Important Questions and Answers:


1. Can we have multiple constructors in Python?
No, Python does not support multiple constructors directly. However, you can achieve similar
functionality using default arguments or by defining a class method that acts as an alternative
constructor.

2. What happens if we do not define an `__init__` method in a class?


If an `__init__` method is not defined, the class can still create objects, but those objects will not
be initialized with any attributes specific to that class unless set explicitly after object creation.

Classes with Multiple Objects


Multiple objects can be created from the same class, each with different attributes:
```python
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade

student1 = Student("Alice", "A")


student2 = Student("Bob", "B")

print(student1.name, student1.grade) # Output: Alice A


print(student2.name, student2.grade) # Output: Bob B
```

Important Points:
 Each object has its own set of attributes.
 Modifications in one object do not affect other objects.

Important Questions and Answers:


1. How do changes in one object’s attributes affect other objects of the same class?
Changes in one object's attributes do not affect other objects of the same class because each
object has its own separate set of instance attributes.

2. Can an object access class attributes?


Yes, an object can access class attributes, but if it tries to modify a class attribute, it creates a
new instance attribute for that object instead of changing the class attribute.

Class Attributes vs. Data Attributes


 Class Attributes: Shared among all instances of a class. Defined directly inside the class.
 Data (Instance) Attributes: Specific to each object. Defined within methods, typically
within the constructor.

Example:
```python
class Employee:
company_name = "Tech Corp" # Class attribute

def __init__(self, name, salary):


self.name = name # Instance attribute
self.salary = salary # Instance attribute

emp1 = Employee("John", 50000)


emp2 = Employee("Jane", 60000)

print(emp1.company_name) # Output: Tech Corp


print(emp2.company_name) # Output: Tech Corp
print(emp1.name) # Output: John
print(emp2.name) # Output: Jane
```

Important Questions and Answers:


1. When should you use class attributes instead of instance attributes?
Class attributes should be used when you want a common attribute that is shared among all
instances of the class. For example, a class attribute can be used for constants or default values
applicable to all instances.

2. Can class attributes be modified? How does it affect objects?


Yes, class attributes can be modified, but changes will reflect across all instances unless an
instance explicitly overrides it with an instance attribute of the same name.
Encapsulation
Encapsulation is the concept of bundling data and methods that operate on the data within one
unit, like a class, and restricting direct access to some of the object’s components.

Example:

```python
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.__balance = balance # Private attribute

def deposit(self, amount):


self.__balance += amount

def withdraw(self, amount):


if amount <= self.__balance:
self.__balance -= amount
else:
print("Insufficient funds!")

def get_balance(self):
return self.__balance

account = BankAccount("John Doe", 1000)


account.deposit(500)
print(account.get_balance()) # Output: 1500
```

Important Points:
 Use underscores (`_`) to indicate private attributes.
 Encapsulation helps in data hiding and abstraction.

Important Questions and Answers:


1. How does encapsulation improve security in software?
Encapsulation restricts direct access to some of an object’s data, which can prevent the
accidental modification of data and ensure that data is used only through defined methods,
enhancing security.

2. What are the benefits of using private attributes?


Private attributes prevent external code from accessing or modifying critical data directly,
ensuring that objects maintain a consistent state through controlled methods only.

Inheritance
Inheritance allows a class (child class) to inherit attributes and methods from another class
(parent class). It promotes code reusability.

Example:
```python
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
pass

class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"

class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"

dog = Dog("Buddy")
cat = Cat("Whiskers")

print(dog.speak()) # Output: Buddy says Woof!


print(cat.speak()) # Output: Whiskers says Meow!
```

Important Points:
 Inheritance helps avoid redundant code.
 The child class inherits attributes and methods of the parent class.

Important Questions and Answers:


1. Can a child class override methods of the parent class?
Yes, a child class can override methods of the parent class to provide a specific implementation
of that method.

2. What is multiple inheritance? Is it supported in Python?


Multiple inheritance is when a class inherits from more than one class. Yes, Python supports
multiple inheritance.

Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common
superclass. It refers to the ability to use a single interface for different data types.

Example:
```python
class Bird:
def fly(self):
print("Flying high!")

class Airplane:
def fly(self):
print("Flying through the sky!")

def let_it_fly(entity):
entity.fly()

bird = Bird()
airplane = Airplane()

let_it_fly(bird) # Output: Flying high!


let_it_fly(airplane) # Output: Flying through the sky!
```
Important Points:
 Polymorphism allows functions and methods to operate on objects of different classes as
long as they have the required method.
 Promotes flexibility and integration of code.

Important Questions and Answers:


1. What is method overriding?
Method overriding occurs when a subclass provides a specific implementation of a method that
is already defined in its superclass. This allows the subclass to modify or extend the behavior of
that method.

2. How does polymorphism enhance code flexibility?


Polymorphism allows objects of different classes to be treated as instances of the same class
through a common interface, making it easy to add new classes with minimal changes to existing
code.

You might also like