Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Chap 5 - Object Oriented Programming in Python

The document discusses object-oriented programming concepts in Python including classes, objects, inheritance, polymorphism and abstraction. It provides examples to explain class definition, instantiating objects, single inheritance, method overriding and the use of namespaces. Design patterns for an Employee class are demonstrated with methods to read, set and display employee information.

Uploaded by

tiwarimanoj1405
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Chap 5 - Object Oriented Programming in Python

The document discusses object-oriented programming concepts in Python including classes, objects, inheritance, polymorphism and abstraction. It provides examples to explain class definition, instantiating objects, single inheritance, method overriding and the use of namespaces. Design patterns for an Employee class are demonstrated with methods to read, set and display employee information.

Uploaded by

tiwarimanoj1405
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Course: Diploma in Computer Engg.

Year/Sem: IIIrd/VIth
Subject: Programming with Python Code: 22616

Chap 5: Object Oriented Programming in Python


1. Explain the concept of class & object with syntax and example.
ANS: A class is a user-defined blueprint or prototype from which objects are created.
Classes provide a means of bundling data and functionality together.
Object: An object is an instance of a class that has some attributes and behavior. Objects
can be used to access the attributes of the class.
Syntax:
class ClassName:
def __init__(self, parameter1, parameter2, ...):
# Initialize instance variables
self.attribute1 = parameter1
self.attribute2 = parameter2
...
def method1(self, parameter1, parameter2, ...):
# Method body
Example:
# Define a simple class named Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# Create an object of the Person class


person1 = Person("Alice", 30)

# Access object attributes


print(person1.name) # Output: Alice
print(person1.age) # Output: 30

# Call object methods


person1.greet()
2. Explain the concept of method overloading with syntax and example.
• ANS: Method overloading is the ability to define the method with the same name but
with a different number of arguments and data types.
• With this ability one method can perform different tasks, depending on the number of
arguments or the types of the arguments given.
• Method overloading is a concept in which a method in a class performs operations
according to the parameters passed to it.
• Python does not support method overloading, that is, it is not possible to define more
than one method with the same name in a class in Python.
Example:
class Calculator:
def add(self, a, b):
return a + b

def add(self, a, b, c):


return a + b + c
calc = Calculator()

# This will raise an error because only the second add method is available due to method
overloading
# print(calc.add(2, 3)) # Error: add() missing 1 required positional argument: 'c'

# Call the overloaded method with three parameters


print(calc.add(2, 3, 4)) # Output: 9
3. Explain the concept of method overriding with syntax and example.
4. Differentiate between method overloading and method overriding in detail with
example.
5. Explain the concept of data hiding and abstraction in detail with example.
6. What is inheritance? List its types with example.
• ANS: One of the core concepts in object-oriented programming (OOP) languages is
inheritance.
• It is a mechanism that allows you to create a hierarchy of classes that share a set of
properties and methods by deriving a class from another class. Inheritance is the
capability of one class to derive or inherit the properties from another class.
• It represents real-world relationships well.
• It provides the reusability of a code. We don’t have to write the same code again and
again.
• Also, it allows us to add more features to a class without modifying it.
Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}
TYPES:
Single Inheritance:
• In single inheritance, a subclass inherits from only one superclass.
Multiple Inheritance:
• In multiple inheritance, a subclass inherits from multiple superclasses.
Multilevel Inheritance:
• In multilevel inheritance, a subclass inherits from another subclass.
Hierarchical Inheritance:
• In hierarchical inheritance, multiple subclasses inherit from a single superclass.
Hybrid Inheritance:
• Hybrid inheritance is a combination of two or more types of inheritance.
7. Explain Single inheritance with example and syntax.
ANS: Single inheritance enables a derived class to inherit properties from a single parent
class, thus enabling code reusability and the addition of new features to existing code
Example:
# Define a superclass
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
pass

# Define a subclass inheriting from Animal


class Dog(Animal):
def __init__(self, name, breed):
# Call superclass constructor to initialize inherited attributes
super().__init__(name)
self.breed = breed

# Override the speak method


def speak(self):
return "Woof!"

# Create an object of the subclass


my_dog = Dog("Buddy", "Golden Retriever")

print(my_dog.name) # Output: Buddy


print(my_dog.breed) # Output: Golden Retriever
print(my_dog.speak()) # Output: Woof!
8. Explain multi level inheritance with example and syntax.
ANS: In multilevel inheritance, features of the base class and the derived class are further
inherited into the new derived class. This is similar to a relationship representing a child
and a grandfather.
EXAMPLE:
# Define superclass
class Animal:
def speak(self):
return "I am an animal"

# Define subclass inheriting from Animal


class Dog(Animal):
def bark(self):
return "Woof!"

# Define subclass inheriting from Dog


class Labrador(Dog):
def breed_info(self):
return "I am a Labrador Retriever"
# Create an object of the subclass Labrador
my_labrador = Labrador()

# Access methods from all levels of inheritance


print(my_labrador.speak()) # Output: I am an animal
print(my_labrador.bark()) # Output: Woof!
print(my_labrador.breed_info()) # Output: I am a Labrador Retriever
9. Explain multiple inheritance with example and syntax.
ANS: When a class can be derived from more than one base class this type of inheritance
is called multiple inheritances. In multiple inheritances, all the features of the base
classes are inherited into the derived class
EXAMPLE:
# Define superclass 1
class Bird:
def fly(self):
return "I can fly"

# Define superclass 2
class Horse:
def run(self):
return "I can run"

# Define subclass inheriting from both Bird and Horse


class Pegasus(Bird, Horse):
def __init__(self, name):
self.name = name

# Create an object of the subclass


my_pegasus = Pegasus("Thunder")

# Access methods from both superclasses


print(my_pegasus.fly()) # Output: I can fly
print(my_pegasus.run()) # Output: I can run

10. Explain use of namespace in python


11. Illustrate class inheritance in Python with an example
ANS: # Define superclass
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age

def speak(self):
return "I am an animal"

# Define subclass inheriting from Animal


class Dog(Animal):
def __init__(self, name, age, breed):
# Call superclass constructor to initialize inherited attributes
super().__init__(name, age)
self.breed = breed

def speak(self):
return "Woof!"

# Define another subclass inheriting from Animal


class Cat(Animal):
def __init__(self, name, age, color):
# Call superclass constructor to initialize inherited attributes
super().__init__(name, age)
self.color = color

def speak(self):
return "Meow!"

# Create objects of the subclasses


my_dog = Dog("Buddy", 5, "Golden Retriever")
my_cat = Cat("Whiskers", 3, "Tabby")

# Access attributes and call methods of both superclass and subclasses


print(my_dog.name) # Output: Buddy
print(my_dog.age) # Output: 5
print(my_dog.breed) # Output: Golden Retriever
print(my_dog.speak()) # Output: Woof!

print(my_cat.name)
12. Design a class Employee with data members: name, department and salary.
Create suitablemethods for reading and printing employee information
CODE:
class Employee:
def __init__(self, name, department, salary):
self.name = name
self.department = department
self.salary = salary

def read_employee_info(self):
self.name = input("Enter employee name: ")
self.department = input("Enter employee department: ")
self.salary = float(input("Enter employee salary: "))

def print_employee_info(self):
print("Employee Information:")
print("Name:", self.name)
print("Department:", self.department)
print("Salary:", self.salary)

# Example usage
employee1 = Employee("John Doe", "IT", 50000)
employee1.print_employee_info() # Output employee info

employee2 = Employee("", "", 0) # Create an employee object with empty data


employee2.read_employee_info() # Read employee info from user
employee2.print_employee_info() # Output entered employee info
13. Illustrate the use of method overriding? Explain with example
14. Create a class Employee with data members: name, department and salary. Create
suitablemethods for reading and printing employee information
CODE:
class Employee:
def __init__(self, name, department, salary):
self.name = name
self.department = department
self.salary = salary

def get_name(self):
return self.name

def get_department(self):
return self.department

def get_salary(self):
return self.salary

def set_name(self, name):


self.name = name

def set_department(self, department):


self.department = department

def set_salary(self, salary):


self.salary = salary

def display_info(self):
print("Employee Information:")
print("Name:", self.name)
print("Department:", self.department)
print("Salary:", self.salary)

# Create an instance of the Employee class


emp = Employee("John Doe", "Engineering", 50000)

# Display employee information


emp.display_info()

15. Python program to read and print students information using two classes
using simpleinheritance.
CODE:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def display_info(self):
print("Name:", self.name)
print("Age:", self.age)

class Student(Person):
def __init__(self, name, age, roll_number):
super().__init__(name, age)
self.roll_number = roll_number

def display_info(self):
super().display_info()
print("Roll Number:", self.roll_number)

# Create an instance of the Student class


student1 = Student("John Doe", 20, "12345")

# Display student information


student1.display_info()
16. Write a Python program to implement multiple inheritance
17. Write a Python program to create a class to print an integer and a character with two
methods having the same name but different sequence of the integer and the character
parameters. For example, if the parameters of the first method are of the form (int n,
char c), then that of the second method will be of the form (char c, int n)
CODE:
class Printer:
def print_int_char(self, n, c):
print("Integer:", n)
print("Character:", c)

def print_char_int(self, c, n):


print("Character:", c)
print("Integer:", n)

# Create an instance of the Printer class


printer = Printer()

# Call the first method with integer and character parameters


printer.print_int_char(5, 'A')

# Call the second method with character and integer parameters


printer.print_char_int('B', 10)

18. Write a Python program to create a class 'Degree' having a method 'getDegree' that prints
"Igot a degree". It has two subclasses namely 'Undergraduate' and 'Postgraduate' each
having a method with the same name that prints "I am an Undergraduate" and "I am a
Postgraduate" respectively. Call the method by creating an object of each of the three
classes.
CODE:
class Degree:
def getDegree(self):
print("I got a degree")

class Undergraduate(Degree):
def getDegree(self):
print("I am an Undergraduate")

class Postgraduate(Degree):
def getDegree(self):
print("I am a Postgraduate")

# Create objects of each class


degree = Degree()
undergrad = Undergraduate()
postgrad = Postgraduate()

# Call the method of each class


degree.getDegree()
undergrad.getDegree()
postgrad.getDegree()

You might also like