Unit 4
Q1 Define
ADT interface. [ 2019-20]
[2021-22]
Solution:
ADT stands for Abstract Data Type, and an ADT
interface is a specification of the behavior and properties of an abstract data
type without specifying the implementation details. It describes the operations
that can be performed on the data type, their parameters and return types, and
any preconditions or postconditions that must hold for these operations to work
correctly.
The ADT interface is typically expressed in terms
of the behavior of the operations, rather than their implementation details,
making it independent of any specific programming language or data structure.
This allows multiple implementations of the same ADT to exist, each with
different performance characteristics or other trade-offs, as long as they
adhere to the same interface.
The purpose of an ADT interface is to provide a
clear and consistent way of working with abstract data types, enabling modular
and reusable code, and promoting good software engineering practices such as
abstraction, encapsulation, and information hiding.
Q2 What is the use of “raise” statement? Describe with an example. [2020-2021]
Solution:
In Python, the “raise” statement is used
to raise an exception manually. It allows a programmer to signal that an error
or exceptional condition has occurred during the execution of a program. When
an exception is raised, the Python interpreter stops executing the current
function and starts looking for an exception handler in the calling functions
or at the top level of the program. If no handler is found, the interpreter
terminates the program and prints a traceback of the error.
Here’s an example of how the “raise” statement can be used:
def divide_by_zero(x, y):
if y ==
0:
raise
ZeroDivisionError(“Cannot divide by zero”)
else:
return x / y
try:
result =
divide_by_zero(10, 0)
print(result)
except ZeroDivisionError as e:
print(“Error:”, e)
In this example, we define a function
“divide_by_zero” that takes two arguments and returns their quotient.
However, if the second argument is zero, we raise a
“ZeroDivisionError” with a custom error message.
In the “try” block, we call the
“divide_by_zero” function with the arguments 10 and 0. Since the
second argument is zero, the function raises an exception, which is caught by
the “except” block. The error message is printed to the console, and
the program continues executing.
Without the “raise” statement, the
program would have crashed with a “ZeroDivisionError” and printed a
traceback of the error. The “raise” statement allows us to handle
exceptional conditions in a structured and controlled way, making our code more
robust and reliable.
Q3 Explain
the use of init function in a class python? [2020-2021]
Solution:
In Python, the __init__() function is a special
method that is used to initialize the state of an object created from a class.
It is also known as the constructor method.
The __init__() function is automatically called
when an object is created from a class, and it can accept arguments that are
used to set the initial state of the object. Inside the __init__() function, we
can define instance variables (also called attributes), which are unique to
each instance of the class.
Here’s an example of how the __init__() function
can be used in a class:
class Person:
def
__init__(self, name, age):
self.name = name
self.age = age
def
say_hello(self):
print(“Hello, my name is”, self.name, “and I am”,
self.age, “years old.”)
p1 = Person(“Alice”, 25)
p1.say_hello()
# Output: “Hello, my name is Alice and I am 25 years old.”
In this example, we define a class called Person
with an __init__() function that accepts two arguments, name and age. Inside
the __init__() function, we define two instance variables, self.name and
self.age, which are initialized with the corresponding arguments.
We also define a method called say_hello() that
prints a message with the person’s name and age.
We then create an object p1 of the Person class,
passing in the arguments “Alice” and 25. We call the say_hello()
method on the p1 object, which outputs the message “Hello, my name is
Alice and I am 25 years old.”
The __init__() function is a powerful tool in
Python classes, as it allows us to define the initial state of objects in a
clear and concise way. By setting instance variables inside the __init__() function,
we can ensure that each object has its own unique state, making our code more
modular and reusable.
Q4 What
is class variable?
Solution
In Python, a class variable is a variable that is
shared by all instances (objects) of a class. It is a variable that belongs to
the class itself, rather than to any particular instance of the class.
Class variables are defined inside the class but
outside of any methods. They can be accessed using the class name followed by
the variable name, or using any instance of the class. If a class variable is
modified using one instance, the new value will be visible to all other
instances of the class.
Here’s an example of how a class variable can be
used in a class:
class Car:
wheels =
4 # class variable
def
__init__(self, make, model):
self.make = make
self.model = model
c1 = Car(“Honda”, “Civic”)
c2 = Car(“Toyota”, “Corolla”)
print(c1.wheels)
# Output: 4
print(c2.wheels)
# Output: 4
Car.wheels = 6
print(c1.wheels)
# Output: 6
print(c2.wheels)
# Output: 6
In this example, we define a class called Car with
a class variable wheels that is set to 4. We then define an __init__() function
that initializes two instance variables, self.make and self.model, with the
arguments passed in during object creation.
We create two instances of the Car class, c1 and
c2, and print their wheels attribute. Since wheels is a class variable, it has
the same value for all instances, so both c1.wheels and c2.wheels are equal to
4.
We then modify the wheels class variable by setting
it to 6. We print the wheels attribute of both c1 and c2 again, and this time
they both have the value 6, since the class variable was changed for all
instances.
Class variables can be useful for defining
attributes or properties that are shared by all instances of a class, such as
constants or default values. However, care should be taken when modifying class
variables, as any changes will affect all instances of the class.
Q5 Define
instance variable.
Solution:
In Python, an instance variable is a variable that
is specific to each instance (object) of a class. Each instance of a class can
have different values for its instance variables.
Instance variables are defined inside the
__init__() method of a class, which is a special method that is called when an
object is created from the class. Inside the __init__() method, we can define
instance variables by assigning values to them using the self-keyword. The self-keyword
refers to the object being created, and allows us to access and modify its
instance variables.
Here’s an example of how instance variables can be
used in a class:
class Person:
def
__init__(self, name, age):
self.name = name
self.age = age
def
say_hello(self):
print(“Hello, my name is”, self.name, “and I am”,
self.age, “years old.”)
p1 = Person(“Alice”, 25)
p2 = Person(“Bob”, 30)
p1.say_hello()
# Output: “Hello, my name is Alice and I am 25 years old.”
p2.say_hello()
# Output: “Hello, my name is Bob and I am 30 years old.”
In this example, we define a class called Person
with an __init__() method that accepts two arguments, name and age. Inside the
__init__() method, we define two instance variables, self.name and self.age,
which are initialized with the corresponding arguments.
We also define a method called say_hello() that
prints a message with the person’s name and age.
We then create two objects, p1 and p2, of the
Person class, passing in different values for name and age. We call the
say_hello() method on both p1 and p2, which outputs a message with their
respective names and ages.
Instance variables are useful for storing data that
is specific to each instance of a class, such as properties or attributes that
may vary from object to object. By using instance variables, we can create
objects that have their own unique state and behavior, making our code more
modular and flexible.
Q6 Define
the term instance.
Solution.
In object-oriented programming, an instance is an
occurrence of a class that represents a specific object with its own unique
state and behavior. An instance, also called an object, is created by
instantiating a class, which involves allocating memory for the object and
initializing its attributes and methods.
For example, consider a class called Car that
represents a car object with properties such as make, model, and year. We can
create instances of the Car class to represent different cars, each with its
own unique values for the properties. Here’s an example:
class Car:
def
__init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
car1 = Car(“Honda”, “Civic”,
2022)
car2 = Car(“Toyota”, “Camry”,
2021)
In this example, we define a Car class with an
__init__() method that initializes the make, model, and year properties of a
car object. We then create two instances of the Car class, car1 and car2, each with
their own unique values for the properties.
Each instance of a class has its own memory space
for storing data and executing methods, and can be accessed and modified
independently of other instances. By creating multiple instances of a class, we
can model complex systems that involve multiple objects with different
properties and behaviors.
Q7 What do
you mean by instantiation?
Solution:
Instantiation is the process of creating an
instance of a class in object-oriented programming. When a class is
instantiated, memory is allocated for the object and its attributes, and the
object is initialized with the values passed as arguments to the constructor
method (__init__() method) of the class.
The process of instantiation involves the following
steps:
- Memory allocation: When an object is created, memory
is allocated to store the object’s attributes and methods. - Constructor call: The constructor method
(__init__() method) of the class is called, which initializes the attributes of
the object with the values passed as arguments. - Object creation: Once the constructor method
completes execution, an object is created with the allocated memory and
initialized attributes.
instantiated in Python:
class Person:
def
__init__(self, name, age):
self.name = name
self.age = age
p1 = Person(“Alice”, 25)
In this example, we define a Person class with an
__init__() method that initializes the name and age attributes of a person
object. We then create an instance of the Person class, p1, passing the values
“Alice” and 25 as arguments to the constructor method.
Once the instantiation process is complete, we can
access the attributes of the p1 object using dot notation, like p1.name and
p1.age. Each instance of the Person class has its own memory space for storing
data and executing methods, and can be accessed and modified independently of
other instances.
Q8 Define
function overloading?
Solution:
Function overloading is a feature in some
programming languages, including Python, that allows a single function name to
be used for different functions with different parameter lists. In other words,
a function can be defined with the same name but different number or types of
parameters, and the appropriate function will be called based on the arguments
passed to the function.
In Python, function overloading is not supported
directly, but it can be achieved using default arguments or variable-length
argument lists. Here’s an example:
def add(a, b, c=0):
return a
+ b + c
result1 = add(2, 3)
result2 = add(2, 3, 4)
print(result1)
# Output: 5
print(result2)
# Output: 9
In this example, we define an add() function with
two required parameters a and b, and an optional parameter c with a default
value of 0. We can call the add() function with two arguments to add only a and
b, or with three arguments to add all three parameters. The appropriate
function implementation will be called based on the number of arguments passed.
Alternatively, we can use variable-length argument
lists to achieve function overloading. Here’s an example:
def add(*args):
if
len(args) == 2:
return args[0] + args[1]
elif
len(args) == 3:
return args[0] + args[1] + args[2]
result1 = add(2, 3)
result2 = add(2, 3, 4)
print(result1)
# Output: 5
print(result2)
# Output: 9
In this example, we define an add() function with a
variable-length argument list *args. We use the len() function to determine the
number of arguments passed, and return the appropriate result based on the
number of arguments. We can call the add() function with two or three
arguments, and the appropriate function implementation will be called based on
the number of arguments passed.
Q9 What do
you understand by “Objects are mutable”?
Solution:
In object-oriented programming, mutable objects are
objects whose internal state can be modified after they are created. This means
that the values of the attributes or properties of a mutable object can be
changed even after the object is instantiated.
In Python, objects such as lists, dictionaries, and
sets are mutable objects. This means that we can modify their contents even
after they have been created. Here’s an example:
my_list = [1, 2, 3]
print(my_list)
# Output: [1, 2, 3]
my_list[1] = 4
print(my_list)
# Output: [1, 4, 3]
In this example, we create a list my_list with
three elements. We then modify the second element of the list to be 4 instead
of 2. The output shows that the list has been modified in place.
On the other hand, immutable objects are objects
whose internal state cannot be modified after they are created. Examples of
immutable objects in Python include strings, integers, and tuples. This means
that we cannot modify their contents once they have been created. Instead, any
modification requires creating a new object with the desired changes.
Here’s an example:
my_string = “hello”
print(my_string)
# Output: hello
my_string = my_string + ” world”
print(my_string)
# Output: hello world
In this example, we create a string my_string with
the value hello. We then concatenate the string with the value world, creating
a new string object hello world. The original string object is not modified,
but instead a new object is created with the desired changes.
Q10
Define__dict__, __bases__, __name__ built-in class attributes Give
example.
Solution:
In Python, classes have several built-in attributes
that provide information about the class and its behavior. Some of these
attributes include:
1. __dict__: This attribute is a dictionary that
contains the namespace of the class. It contains the class’s methods,
properties, and attributes, and can be accessed or modified at runtime. Here’s
an example:
class MyClass:
def
__init__(self, x, y):
self.x = x
self.y = y
def
my_method(self):
print(“Hello, world!”)
# Accessing __dict__
print(MyClass.__dict__)
In this example, we define a class MyClass with a
constructor that takes two arguments x and y, and a method my_method(). We can
access the __dict__ attribute of the class using the class name, and it will
return a dictionary containing the class’s attributes.
2. __bases__: This attribute is a tuple that contains the base
classes of the class in the order they are searched for attributes. It can be
useful for checking the inheritance hierarchy of a class. Here’s an example:
class MyBaseClass:
pass
class MyClass(MyBaseClass):
def
__init__(self, x, y):
self.x = x
self.y = y
def
my_method(self):
print(“Hello, world!”)
# Accessing __bases__
print(MyClass.__bases__)
In this example, we define a base class MyBaseClass
and a derived class MyClass that inherits from MyBaseClass. We can access the
__bases__ attribute of the MyClass class to see that it inherits from
MyBaseClass.
3. __name__: This attribute is a string that contains the name
of the class. It can be useful for debugging or for dynamically constructing
class names. Here’s an example:
example:
class MyClass:
def
__init__(self, x, y):
self.x = x
self.y = y
def
my_method(self):
print(“Hello, world!”)
# Accessing __name__
print(MyClass.__name__)
In this example, we define a class MyClass. We can
access the __name__ attribute of the class to get its name as a string.
Q11 List the order of file operations in Python.
Solution:
In Python, file operations typically follow a sequence of steps that can
be summarized as:
- Open the
file: This is done using the open() function, which
returns a file object that allows you to access the file’s contents. - Read or
write to the file: Once the file is opened, you can perform read or
write operations on it. Reading is done using the read() method, while writing
is done using the write() method. - Close the
file: After you are done reading or writing to the
file, you should close it using the close() method. This ensures that any
resources associated with the file are properly released.
is properly initialized, used, and cleaned up. Here’s an example of how these
operations might be performed in Python:
# Open the file
with open(“myfile.txt”, “r”) as f:
# Read from the file
contents = f.read()
# Do something with the file
contents
print(contents)
# Close the file (automatically done by the “with” statement)
In this example, we open a file named “myfile.txt” in read
mode using the open() function, and then read its contents using the read()
method. We then print the contents to the console. Finally, we close the file
using the with statement, which automatically closes the file for us when we
are done.
Q12 What are
the basic methods performed on directories?
Solution:
In Python, there are several basic methods that can be performed on
directories:
1. Creating a
directory: This is done using the os.mkdir() method, which
creates a new directory with the specified name. For example:
import os
os.mkdir(“mydir”)
This creates a new directory named “mydir”.
2. Removing a
directory: This is done using the os.rmdir() method, which
removes the specified directory. For example:
import os
os.rmdir(“mydir”)
This removes the directory named “mydir”.
3. Changing the
current directory: This is done using the os.chdir() method, which
changes the current working directory to the specified directory. For example:
import os
os.chdir(“/path/to/mydir”)
This changes the current working directory to the directory located at
“/path/to/mydir”.
4. Listing the
contents of a directory: This is done using the
os.listdir() method, which returns a list of the files and directories
contained in the specified directory. For example:
import os
contents = os.listdir(“/path/to/mydir”)
print(contents)
This prints a list of the files and directories contained in the
directory located at “/path/to/mydir”.
5. Checking if
a directory exists: This is done using the os.path.exists() method,
which returns True if the specified directory exists, and False otherwise. For
example:
import os
if os.path.exists(“mydir”):
print(“Directory
exists!”)
else:
print(“Directory does not
exist.”)
This checks if a directory named “mydir” exists and prints a
message indicating whether or not it exists.
Q13 Write
some built-in exception in Python?
Solution:
Python has several built-in exceptions that can be raised during program
execution. Some of the most commonly used exceptions in Python include:
SyntaxError: Raised when the syntax of a Python program is incorrect.
IndentationError: Raised when the indentation of a Python program is
incorrect.
NameError: Raised when a variable or function name is not defined.
TypeError: Raised when an operation or function is applied to an object
of inappropriate type.
ValueError: Raised when a built-in operation or function receives an
argument that has the right type but an inappropriate value.
ZeroDivisionError: Raised when division or modulo by zero takes place
for all numeric types.
IOError: Raised when an I/O operation (such as reading or writing a
file) fails for an I/O-related reason.
IndexError: Raised when an index is out of range for a sequence.
KeyError: Raised when a dictionary key is not found.
AttributeError: Raised when an attribute reference or assignment fails.
Here’s an example of how to raise a ValueError exception:
x = -5
if x < 0:
raise ValueError(“Number
cannot be negative”)
In this example, we raise a ValueError exception with a custom error
message if the variable x is less than 0. This will cause the program to stop
executing and display an error message.
Q14 What are the various file positions methods?
Solution:
In Python, there are three file position methods that can be used to
move the file pointer to a specific position within a file:
1. seek(offset[, whence]): This method sets the file’s current position,
measured from the beginning of the file. The offset argument specifies the
number of bytes to be moved from the position specified by the whence argument,
which can be one of three values: 0 (the beginning of the file), 1 (the current
position), or 2 (the end of the file). For example, to move the file pointer to
the beginning of the file, you would use:
file.seek(0)
2. tell(): This method returns the current position of the file pointer
within the file, as an integer number of bytes from the beginning of the file.
For example:
position = file.tell()
truncate([size]): This method truncates the file to a specified size. If
the size argument is not provided, the file will be truncated at the current
position of the file pointer. For example, to truncate the file at the current
position of the file pointer, you would use:
file.truncate()
Note that these methods only apply to files that are opened in binary
mode (“rb” or “wb”) or in a mode that allows for binary
access (“r+b”, “w+b”, etc.). If a file is opened in text
mode (“r”, “w”, etc.), the behavior of these methods is
undefined.
You may Like to Read
this
PYTHON PROGRAMMING ALL STUDY MATERIAL || 99+ MOST IMPORTANT
QUESTION WITH SOLUTION