Python 3 4 PRGMS
Python 3 4 PRGMS
Program:
def recursive_factorial(n):
if n == 1:
return n
else:
return n*recursive_factorial(n-1) #function calling itself
#taking input from the user
number = int(input("User Input : "))
print("The factorial of", number, "is", recursive_factorial(number))
output:
User Input: 4
The factorial of 4 is 24
Write a program to implement inheritance and polymorphism
Inheritance
One of the major advantages of Object Oriented Programming is re-use.
Inheritance is one of the mechanisms to achieve the same. Inheritance allows
programmer to create a general or a base class first and then later extend it to
more specialized class. It allows programmer to write better code.
syntax to create a derived class is −
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
Polymorphism (“MANY FORMS”)
Polymorphism is an important feature of class definition in Python that is
utilized when you have commonly named methods across classes or subclasses.
This permits functions to use entities of different types at different times. So, it
provides flexibility and loose coupling so that code can be extended and easily
maintained over time.
This allows functions to use objects of any of these polymorphic classes without
needing to be aware of distinctions across the classes.
PROGRAM:
# Base class
class Person:
def __init__(self, name):
self.name = name
def role(self):
pass
# Derived class 1
class Student(Person):
def role(self):
return f"{self.name} is a student studying."
# Derived class 2
class Professor(Person):
def role(self):
return f"{self.name} is a professor teaching."
In this example:
1. Person is the base class with a constructor (__init__) to initialize the
name of the person and an empty method role.
2. Student and Professor are derived classes that inherit from Person and
override the role method.
3. The person_role function demonstrates polymorphism by calling the role
method on different types of Person objects (Student and Professor).
This simple program shows how inheritance allows Student and Professor to
inherit properties from the base class Person, and how polymorphism enables
the person_role function to work with different person objects.