Classes provide a means of bundling data and functionality together. Object-oriented programming organizes software around objects rather than functions and logic. A superclass is a class that other classes inherit from, becoming subclasses. Subclasses add functionality like new variables or methods. Exception handling uses try, except, else, and finally blocks to handle errors gracefully. Try blocks contain code that may cause exceptions, except blocks handle specific exceptions, else blocks contain code that runs if no exceptions occurred, and finally blocks always execute.
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 ratings0% found this document useful (0 votes)
41 views13 pages
Mark: 1-What Is The Class
Classes provide a means of bundling data and functionality together. Object-oriented programming organizes software around objects rather than functions and logic. A superclass is a class that other classes inherit from, becoming subclasses. Subclasses add functionality like new variables or methods. Exception handling uses try, except, else, and finally blocks to handle errors gracefully. Try blocks contain code that may cause exceptions, except blocks handle specific exceptions, else blocks contain code that runs if no exceptions occurred, and finally blocks always execute.
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
You are on page 1/ 13
{1} mark
1- what is the class
Classes provide a means of bundling data and functionality together. Class creates a user-defined data structure, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object 2- what is mean by object-oriented programming Object-oriented programming (OOP) is a computer programming model that organizes software design around data, or objects, rather than functions and logic. An object can be defined as a data field that has unique attributes and behavior. 3- what is super class a class from which other classes inherit code is called a superclass. Furthermore, the class that inherits the code is called a subclass of that superclass 4- what is mean by sub class Subclasses are classes that can be derived from a parent class by adding some functionality, such as new object variables or new methods. 5- what is future of oops 1- Classes. 2- Objects. 3- Inheritance. 4- Polymorphism. 5- Data Abstraction and Encapsulation. 6- Inheritance? Inheritance is the procedure in which one class inherits the attributes and methods of another class, inheritance helps the programmer to: Reduce code redundancy. Provides code reusability. Reduces source code size and improves code readability.
7- types of inheritance 1- Single inheritance. 2- Multiple inheritances. 3- Multilevel inheritance. 4- Hierarchical inheritance. 5- Hybrid inheritance. 8- use of else keyword in exception handling You can use the else keyword to define a block of code to be executed if no errors were raised: Example. In this example, the try block does not generate any error: try: print("Hello") except: print ("Something went wrong") else: print ("Nothing went wrong")
9- when does type error occur?
The Type Error object represents an error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. 10-what is the use of type error? Type Error is one among the several standard Python exceptions. Type Error is raised whenever an operation is performed on an incorrect/unsupported object type. 11-what is the use of raise keyword? The raise statement allows the programmer to force a specific exception to occur. The sole argument in raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from Exception) 12- list out the types of error Syntax error or Compile time error Run time error Logical error 13-how can you call the method of base class without creating instance? you can use the methods of a class without creating an instance or object of that class through the use of the Keyword "Static". 14-which operator is used for accessing member of class via object? a dot (.) operator 15-if it compulsory to have except block in exception handling if no then write reason The output is: The Except block will execute when the zero-division error does not match. If default except block is defined then compulsory it must be a last except block; otherwise, we will get a syntax error. 16-when does the zero-division error occur? A Zero Division Error is raised when the second argument of a division or modulo operation is zero. 17-if it compulsory to have finally block in exception handling if no then write reason The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. ... Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues. 18-name the class which is base class for all exception Base Exception. The Base Exception class is, as the name suggests, the base class for all built-in exceptions in Python. {4} marks 1- write a program using lambda function to find maximum of two number max = lambda a, b: x if (a > b) else b print (max (5, 6)) Output: 6 2- list the special function of comparison function overloading The comparison operators (<, <=, >, >=, == and! =) can be overloaded by providing definition to __lt__, __le__, __gt__, __ge__, __eq__ and __ne__ magic methods. Following program overloads == and >= operators to compare objects of distance class.
3- list out any four built in exception class in python
1.exception Base Exception
2.exception Exception
3.exception Buffer Error
4. exception Arithmetic Error.
4- state any two points differences between class and object
5- what is the use of try and except block in exception handling?
A. The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program’s response to any exceptions in the preceding try clause. B. Try and Except statement is used to handle these errors within our code in Python. The try block is used to check some code for errors i.e. the code inside the try block will execute when there is no error in the program. Whereas the code inside the except block will execute whenever the program encounters some error in the preceding try block. {6} marks 1- write the python code for zero division error and value error while (True):
try:
a = int (input ("please enter an integer value "))
b = int (input ("please enter an integer value ")) c=a/b except ValueError: print ("Oops! you entered non integer value please enter a gain ") except ZeroDivisionError: print ("it is a Zero division Error") break else: print (c) Break
2- write a code for demonstrate the single level inheritance
# Base class
class Parent:
def func1(self):
print ("This function is in parent class.")
# Derived class
class Child (Parent):
def func2(self):
print ("This function is in child class.")
# Driver's code
object = Child ()
object.func1()
object.func2()
3- write a code for handling zero division error by taking the input from the user def input_numbers():
a = float (input ("Enter first number:"))
b = float (input ("Enter second number:"))
return a, b
x, y = input_numbers()
try:
print(f"{x} / {y} is {x/y}")
except ZeroDivisionError:
print ("Cannot divide by zero")
x, y = input_numbers()
4- write a script for how to handle exception with finally block
def divide (x, y):
try:
result = x // y
except ZeroDivisionError:
print ("Sorry! You are dividing by zero ")
else:
print ("Yeah! Your answer is:", result)
finally:
print ('This is always executed')
divide (3, 0)
Output:
Sorry! You are dividing by zero
This is always executed
5-explain about constructor with simple example
constructor is a special kind of method which is used for initializing the instance members when we create the object of a class. Defining constructor: a constructor always has a name init and the name init is prefixed and suffixed with a double underscore(__). We declare a constructor using def keyword, Type of constructor: 1. Parameterized Constructor 2. Non-parameterized Constructor Example: class Myclass: def __init__(self): self.num=100 def read_number(self): print(self.num) obj = Myclass() obj.read_number() Output: 100
6- explain try, except,finally and else block in exception handling
Try: This block will test the excepted error to occur Except: Here you can handle the error Else: If there is no exception then this block will be executed Finally: Finally block always gets executed either exception is generated or not The syntax: try: # Some Code.... except: # Handling of exception (if required) else: # execute if no exception finally: # Some code .....(always executed) Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause. Try block: has the statements that can raise exceptions Except block: has the statements that handle the exception Else block: must be present after all the except blocks. The code enters the else block only if the try clause does not raise an exception. Finally block executes always if there is exception or not
7- write a script to demonstrate the how to handle exception and execute else block in exception handling Else block: must be present after all the except blocks. The code enters the else block only if the try clause does not raise an exception. The code: num1 = 51 num2 = 3 try: num3 = num1 / num2 except ZeroDivisionError: print ("Oops! you can't divide by zero ") else: print ("the result of division is ", num3)
8- write the python program to create class name:parrot attributes: name, age and method : CanSing, CanDance demonstrate how to access instance of attribute and method class Parrot:
name = "roky"
age = "age 3 "
def CanSing(self):
print(self.name , "can sing ",)
def CanDance(self):
print(self.name , "can Dance ",)
Rodger = Parrot ()
print(Rodger.name)
print(Rodger.age)
Rodger.CanSing()
Rodger.CanDance()
Output:
roky
age 3
roky can sing
roky can Dance
9- explain about lambda function with its syntax and write a lambda function that double the input element Python Lambda Functions are anonymous function means that the function is without a name. the lambda keyword is used to define an anonymous function in Python. This function can have any number of arguments but only one expression, which is evaluated and returned. The syntax:
lambda arguments: expression
The code: list1 = [1,2,3,4,5,6]
list2 = map (lambda x : x*2 , list1 )
print (list(list2))
the map function is used to apply a particular operation to every element in a sequence it takes 2 parameters: a function then the sequence
The filter function is used to select some particular elements from a sequence of elements. it takes 2 parameters: a function then the sequence
{8} marks 1- explain the class and instance of variable explain with simple code Class variable: A Python class variable is shared by all object instances of a class. Class variables are declared when a class is being constructed. They are not defined inside any methods of a class. all instances of the class will be able to access the class variable. Like regular variables, class variables can store data of any type. we can access it when we create an object of our class. In order to see the value of the class variable in our class, we use the dot notation. ((object_name.classVariable_name)) and class variables can also be changed, just like any other type of variable. ((object_name.classVariable_name = value)) Instance variable: Python instance variables are owned by an instance of a class. The value of an instance variable can be different depending on the instance with which the variable is associated. Python instance variables are owned by an instance of a class. The value of an instance variable can be different depending on the instance with which the variable is associated. ((for which instance that variable is.)). This is unlike a class variable where the variable can only have one value that you assign. Instance variables are declared inside a class method. We can assign values to an instance variable when we declare a class. We do this by specifying the values we want to assign as arguments when we declare the class class Dog:
kind = 'canine'
def __init__(self, name):
self.name = name
d = Dog('Fido')
e = Dog('Buddy')
d.kind
e.kind
d.name
e.name
2- write a script for demonstrate the user defined exception
class MyError(Exception):
# Constructor or Initializer def __init__(self, value):
self.value = value
def __str__(self):
return(repr(self.value))
try:
raise(MyError(3*2))
except MyError as error:
print('A New Exception occured: ',error.value)
3- write a python script to handle the exception while opeing
or reading data from file import csv
fName = "aFile.csv"
try:
with open(fName, 'rb') as f:
reader = csv.reader(f)
for row in reader:
pass #do stuff here
except IOError:
print "Could not read file:", fName
4- explain the self-parameter of python with the example program self represents the instance of the class. By using the “self” keyword we can access the attributes and methods of the class in python. It binds the attributes with the given arguments.
The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on.
class check:
def __init__(self): print("Address of self = ",id(self))
obj = check()
print("Address of class object = ",id(obj))
5-explain the oops terminology---------class, instance, function overloading, inheritance,
polymorphism
Class: The class can be defined as a collection of objects. It is a logical entity that has some specific attributes and methods. And it is a user defined blueprint or prototype from which objects are created. attributes are the variables of a class and the methods are the function of that class. Class created by ‘class’ keyword. Syntax: class ClassName: statements... instance: it is an Object of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. An object consists of : State: It is represented by the attributes of an object. It also reflects the properties of an object. Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects. Identity: It gives a unique name to an object and enables one object to interact with other objects. Function overloading: Method overloading means a class containing multiple methods with the same name but may have different arguments. Basically, python does not support method overloading, but there are several ways to achieve method overloading. Though method overloading can be achieved, the last defined methods can only be usable. Inheritance: Inheritance is the capability of one class to derive or inherit the properties from another class. The benefits of inheritance are: It represents real-world relationships well. 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. 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. And it has many types like: - single inheritance class derived-class (base class): <class-suite> - multiple inheritance class Base1: <class-suite> class Base2: <class-suite> class BaseN: <class-suite> class Derived(Base1, Base2, ...... BaseN): <class-suite> - Multilevel inheritance class class1: <class-suite> class class2(class1): <class suite> class class3(class2): <class suite> Polymorphism: - The word polymorphism means having many forms. The literal meaning of polymorphism is the condition of occurrence in different forms. - Polymorphism is a very important concept in programming. It refers to the use of a single type entity (method, operator) to represent different types in different scenarios - Polymorphism in python is used for a common function name that can be used for different types. - This concept is widely applied in object-oriented based python programming. - polymorphism is also implemented in python for different purpose commonly: 1- Operator overloading 2- Method overloading 3- Method overriding
6- write a program for handling a value error, type error, and zero division error? ValueError: while(True): try: num1 = int(input("please enter a value ")) num2 = int(input("please enter a value ")) num3 = num1 + num2 except ValueError: print ("please enter an integer value ") else: print ("the sum of the numbers are ", num3 ) Break TypeError: v1 = ['studetn','MU','7th','CS'] v2 = [0,1,"2",3] for i in range( len(v1) ): try: print (v1[v2[i]]) except TypeError: print ("Type Error : please Check list of indices") ZeroDivisionError: o while(True): try: num1 = int (input("please enter a value ")) num2 = int (input("please enter a value ")) num3 = num1 / num2 #except ValueError: #print ("please make sure that you entered integer values ") except ZeroDivisionError: print ("you cant devide by zero ") else: print ("the sum of the numbers are ", num3 ) break For three: while(True): try: num1 = input("please enter a value ") num2 = input("please enter a value ") num3 = num1 / num2 except ValueError: print ("please make sure both variables same type") except ZeroDivisionError: print ("you cant devide by zero ") except TypeError: print ("please check the data types of your index ") else: print ("the sum of the numbers are ", num3 ) break