82 - Experiment - No - 2 (Python)
82 - Experiment - No - 2 (Python)
Goykar
Theory:
Class:
class ClassName:
# Statement-1
# Statement-N
Objects
An object consists of :
Function in python:
As you already know, Python gives you many built-in functions like print(),
etc. but you can also create your own functions. These functions are
called user-defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple
rules to define a function in Python.
Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) ).
The code block within every function starts with a colon (:) and is
indented.
Syntax:
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them
in the same order that they were defined.
Exception Handling:
Python uses try and except keywords to handle exceptions. Both keywords
are followed by indented blocks.
Syntax:
try :
except :
If the Python program contains suspicious code that may throw the
exception, we must place that code in the try block. The try block must be
followed with the except statement which contains a block of code that will be
executed if there is some exception in the try block.
Example:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except Exception:
Roll No: 82 Name: Abhishek A. Goykar
else:
Inheritance:
Inheritance is the capability of one class to derive or inherit the
properties from another class. The benefits of inheritance are:
1. It represents real-world relationships well.
2. It provides 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.
3. It is transitive in nature, which means that if class B inherits from
another class A, then all the subclasses of B would automatically
inherit from class A.
a) Simple Inheritance:
In inheritance, the child class acquires the properties and can access
all the data members and functions defined in the parent class. A child
class can also provideits specific implementation to the functions of
the parent class.
Syntax:
class BaseClass1
#Body of base class
class DerivedClass(BaseClass1):
#body of derived – class
b) Multiple inheritance
Syntax:
class A:
# variable of class A
# functions of class A
class B:
# variable of class A
# functions of class A
Code:
class Maths:
def GetInput(self):
class Division(Maths):
def Div(self):
try:
self.div=self.n1/self.n2
except Exception:
exit()
Roll No: 82 Name: Abhishek A. Goykar
class Result(Division):
def output(self):
print("Division of %s" % self.n1,"and %s is" % self.n2, self.div)
obj=Result()
obj.GetInput()
obj.Div()
obj.output()
Roll No: 82 Name: Abhishek A. Goykar
Output:
Roll No: 82 Name: Abhishek A. Goykar
Conclusion: