Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

Predict the output of the following code snippet:ptr=40def result():print ptrptr=90def func(var):if var<=60:ptr=30print ptrresult()func(60)func(70)

Answer»

UnboundLocalError: local variable ‘ptr’ referenced before assignment.

2.

How do you implement abstract method in Python? Give an example for the same.

Answer»

Abstract method : An unimplemented method is an abstract method. When an abstract method is declared in a base class, the driven class has to either define the method or raise” Nothlmplemented Error”

class Shape (object):

def findArea (self):

pass

class Square (Shape):

def_ init_(self, side):

self, side = side

def find Area (self):

return self.side*self.side

Note: We can use @ abstract method to enable parent class method to be executed.

3.

Explain how objects of a class can be defined?

Answer»

The objects are declared after a class is defined. The object declaration create object of that class and memory is allocated for the created object. The object are created using the following syntax:
classname objectname1, objectname2,……………;
for example
student obj1, obj2;
the obj1 and obj2 are the objects of class type student.
The object names are used to access the data members through member functions by invoking member functions.
For example
obj1.getdata(5, 25);

here, getadata() is the member function of a class student and function call is give using object obj1 which assign the value 5 and 25 to the data members of the class. The memory is allocated separately for data members of each object.

4.

What is meant by referencing member functions inside class definition and outside class definition?

Answer»

In C++, the member functions can be coded in two ways :

  1. Inside class definition
  2. Outside class definition using scope resolution operator (::)

The code of the function is same in both the cases, but the function header is different as explained below:
1. Inside Class Definition:

When a member function is defined inside a class, we do not require to place membership label along with the function name. We use only small functions inside the class definition and such functions are known as inline functions.
In case of inline function, program execution is faster but memory penalty is there.

2. Outside Class Definition Using Scope Resolution Operator (::)

The member function declared in the class must be defined outside the class. Here the operator :: known as scope resolution operator helps in defining the member function outside the class.
In this case the function’s full name (qualified_name) is written as shown: Name_of_the_class :: function_name()
The syntax for a member function definition outside the class definition is:

return type name_of_the_class::function_name (argument list)
{
body of function;
}

5.

What are the characteristics of member function outside a class?

Answer»

The member functions declared outside a class has the following characteristics:

  1. Data type and number of argument in member function must be same as data types and number of data declared in class definition.
  2. Type scope resolution operator (::) helps in defining the member function outside the class. It also identifies the function as a member of particular class.
  3. The different classes can use same member function names. Membership label will resolve their scope limiting a particular class.
  4. Member function can access private and protected data of a class, but not a non-member function.
6.

Write the syntax and example for class declaration.

Answer»

Syntax: classname objectname1, objectname2, …. ,objectname………… n ;
For example, Largest ob1,ob2; //object declaration will create two objects ob1 and ob2 of largest class type.

7.

What is an object?

Answer»

The object is an instance of a class.

8.

Mention the access specifiers used with a class.

Answer»

The access specifiers used with a class are private, protected and public.

9.

Describe access specifiers in a class.

Answer»

The data members and member functions can be accessed using access specifiers. They define the scope of members. The members of class are classified based on private/public/protected members.

1. Private members:
The member data and members functions defined using access specifier private, can be accessed by member functions of that class only. Non-members of . the class cannot access private members of the class. If no access specifier is mentioned for the members, then it is treated as private members.

2. Protected members:
The protected members are similar to private members of a class in a single class. But, if a class is derived from an existing class, then protected members of the base class are accessible to the derived class.

3. Public members:
The public members can be accessed by member functions of the class and non member function (outside the class) of the class. The public member functions can access private, protected and public data members of the class.

10.

Which access specifier is implicitly used in a class?

Answer»

The private access specifer is implicitly used in a class.

11.

Is it possible to access data outside a class?

Answer»

Yes, the public members can be accessed by member functions of the class and non-member function (outside the class) of the class.

12.

What is the significance of using access specifiers? Mention different access specifiers.

Answer»

The data members and member functions can be accessed using access specifiers. They define the scope of members. The different access specifiers are private, protected and public.

13.

What is a member function?

Answer»

The member functions are behaviour of a class and can access or manipulate data members without passing them as parameters.

14.

What are data members?

Answer»

The variables are declared inside the class and are called data members.

15.

Which type of data members are accessible outside a class?

Answer»

The public members can be accessed by member functions of the class and non member function (outside the class) of the class.

16.

What are the two types of members referenced in a class?

Answer»

The two types of member referenced in a class are data members and member functions.

17.

How are class members referenced? Discuss with suitable example.

Answer»

The class members are referenced using dot (.) operator. The public data members of a class can be accessed using dot (.) operator using objects of that class.
For example, objectname . datamember;
The member function is invoked by a object name dot operator and member function name.
For example, obj1.getdata();

18.

Explain protected access.

Answer»

The protected members are similar to private members of a class in a single class. But, if a class is derived from an existing class, then protected members of the base class are accessible to the derived class.

19.

Write short notes on public access specifiers.

Answer»

The public members of a class can be accessed by member functions of that class and also non member functions (outside the class) of the class. The public member functions can access private, protected and public data members of the class.

20.

Define the term public access.

Answer»

The public members can be accessed by member functions of the class and non member function (outside the class) of the class.

21.

Mention the operator used to access members of a class?

Answer»

The dot (.) is used to access members of a class.

22.

What is the significance of scope resolution operator?

Answer»

The operator :: known as scope resolution operator helps in defining member function outside the class.

23.

Write the differences between class definition and class declaration.

Answer»

A class definition is a process of naming a class and data variables and interface operations of the class. A class declaration specifies the representation of objects of the class and set of operations that can be applied to such objects.

24.

How are objects of a class declared? Give an example.

Answer»

Syntax: classname objectname1, objectname2, …. ,objectnamen ;
For example, Largest ob1,ob2; //object declaration

25.

What is meant by an array of objects?

Answer»

The array of class type is known as array of objects.

26.

Create the class SOCIETY with following information: society_name,house_no,no_of_members,flat, income Methods : (i) An _init_ method to assign initial values of society_name as “Surya Apartments”, flat as “AType”, house_.no as 20, no_of_ members as 3, income as 25000.  (ii) Inputdata()-To read data members (society,house_no,no_of members & income) and call allocate_flat(). (iii) allocate_flat( )-To allocate flat according to incomeIncomeFlat>=25000A Type>=20000 and <25000B Type<15000C TypeShowData() to display the details of the entire class.

Answer»

class SOCIETY:

# constructor to create an object

def init (self):

#constructor

self. society_name=‘Surya Apartments’

self.house_no=20

self.no_of_members=3

self.flat=AType’

self.income=25000

def Inputdata(self):

self. society_name = raw_input (“Enter Society Name”)

self.house_no=input(“Enter House Number”)

self.no_of_members = input (“Enter No. of members”)

self.income = float(raw_input (“Enter income”))

def Allocate_Flat(self):

if self.income >= 25000:

self.flat = AType’

elif self.income >= 20000 and self.income < 25000 :

self.flat = ‘BTÿpe’ else:

self.flat = ‘CType’

def Showdata(self):

print “Society Name”,

self.society_name

print “House_No”,

self.house_no print “No.of members”,

self.no_of mem-bers

print “Flat Type”,

self.flat print “Income”,

self.income

S = SOCIETY))

S.InputdataO

S.Allocate_Flat()

S.ShowdataO

27.

Define a class PRODUCT in Python with the following specifications :Data members:Pid – A string to store product.Pname -A string to store the name of the product. Peostprice – A decimal to store the cost price of the productPsellingprice – A decimal to store Selling Price Margin- A decimal to be calculated as Psellingprice- PcostpriceRemarks- To store “Profit” if Margin is positive else “Loss’ if Margin is negativeMember Functions :A constructor to initialize All the data members with valid default values.A method SetRemarks() that assigns Margin as Psellingprice – Peostprice and sets Remarks as mentioned below :MarginRemarks&lt;0(negative)Loss&gt;0(positive)ProfitA method Getdetails() to accept values for Pid. Pname,Psellingprice and invokes SetRemarks() method.A method Setdetails () that displays all the data members.

Answer»

class PRODUCT:

def init (self):

self. Pid = self. Pname = self. Peostprice = 0.0 self. Psellingprice = 0.0 self. Margin = 0.0 self. Remarks = def SetRemarks (self) :

self . Margin = self.Psellinrprice-self. Peostprice

if (self.Margin < 0) :

self. Ramarks = “Loss”

else:

self. Remarks = “Profit” defGetdetails (self):

self.Pid = rawjnput (“Enter Product Id”)

self.Pname = rawjnput (“Enter Product Name”)

self.Peostprice = input (“Enter Cost Price”)

self.Psellingprice = input (“Enter Selling Price”)

self. SetRemarks ( ) def Setdateils (self) :

print “Product Id” ,

self.Pid print “Product Name”,

self.Pname print “Cost Price”,

self.Pcostprice print “Selling Price”,

self.Esellingprice print “Margin : ” ,

self.Margin print “Incurred :” ,

self.Remarks

28.

Write a Python program using classes and objects to simulate result preparation system for 20 students. The data available for each student includes: Name, Roll no, and Marks in 3 subjects. The percentage marks and grade are to be calculated from the following information:Percentage Of MarksGrade80 to 100A60 to 80B45 to 60CLess than 45DGRADE FORMULAAlso demonstrate constructor overloading.

Answer»

# constructor to create an object

def init (self,s=None):

#non-copy constructor if s==None:

self.rollno = 0 self.name = ‘ ’

self.marks = [0,0,0]

self.avg = 0.0 self.grade = ‘ ’

# copy constructor else:

self.rollno = s.rollno self.name = s.name self.marks = s.marks self.avg = s.avg

self.grade = s.grade

def read (self):

# This function gets the details of a student from the user

selfrollno=iaw_input(“Enter roll number.-’)

self.name = raw_input(“Enter name:-”) s=0

for i in range(0,3):

self.marks [i] = int(r a w_input (“Enter the marks ?”)) s = s + self.marksfi] self.avg = s/3

if(self.avg>60):

self.grade=‘A’

elif self.avg>40:

self.grade=‘B’

else:

self.grade=‘C’

def display (self):

# This function prints each student’s details

print self.rollno,“\t”, self, name, “\t\ t”,

self.grade s = StudentO studlist = []

num = int(raw_input(“Enter no. of students:-’’))

for i in range(O.num):

s.read()

studlist. append(Student(s))

print “ STUDENT REPORT \n”

print “***********************************\n”

print “RollNo \t Name \t\t Grade”

print “*******************************************\n”

for i in range(0,num):

studlist[i] .displayO

#Initialize avg as the first student’s avg maxavg = studlist[0].avg totavg = 0

for i in range(l.num):

totavg = totavg + studlist[i].avg if studlist[i].avg > maxavg: maxavg = studlist[i].avg

topper = studlist[i].name totavg = totavg/num

print “Class topper is”,studlist[i],name,“with average”, studlist [i]. avg

print “Class average is”,totavg

class Student:

29.

What do you mean by name mangling? Support your answer with relevant example.

Answer»

Name mangling of the double underscore makes the most sense for achieving “private-ness”. Now when a function is called from the ‘self’ instance and it notices that it starts with ‘_’, it just performs the name mangling right there. Name mangling is helpful for letting sub-classes override methods without breaking intra class method calls.

30.

Explain _str_ with an example.

Answer»

_str_ returns a string representation of a Point object. If a class provides a method named _str _, it overrides the default behavior of the Python built-in

_str_ function.

>>> p = Point(3, 4)

>>> str(p)

‘(3,4)’

Printing a Point object implicitly invokes _str_ on the object, so*- defining _str_

also changes the behavior of print:

>>> p = Point(3,4)

>>> print p(3,4)

31.

Differentiate between reference counting and automatic garbage collection with respect to Python.

Answer»

Reference counting works by counting the number of times an object is referenced by other objects in the system. Python’s garbage collector runs during program execution and is triggered when an object’s reference count reaches zero. An object’s reference count changes as the number of aliases that point to it change. 

An object’s reference count increases when it is assigned a new name or placed in a container (list, tuple or dictionary). The object’s reference count decreases when it is deleted with del, its reference is reassigned, or its reference goes out of scope. When an object’s reference count reaches zero, Python collects it automatically. 

Automatic garbage collectiomPython deletes the objects which are not required, may it be built-in types or class instances, through the process named garbage collection. When the number of allocations minus the number of de-allocations is greater than the threshold number, the garbage collector is run and the unused block of memory is reclaimed. 

One can inspect the threshold for new objects by loading the garbage collector (GC) module and asking for garbage collection thresholds.

32.

Differentiate between class attributes and instance attributes.

Answer»

The difference is that the attribute on the class is shared by all instances. The attribute on an instance is unique to that instance.

33.

Give one word for the following:a. A sort of constructor in Python ______b. A region of a Python program where a namespace is directly accessible.______c. It returns the docstring of a class.______d. It returns the string representation of the object. ______e. A method used to delete an attribute. ______

Answer»

a. _init_

b. scope

c. _doc_

d. _str_

e. _delattr_ ()

34.

Define a namespace. Give examples of namespaces with respect to Python.

Answer»

A namespace is a mapping from names to objects. Examples of namespaces are built-in names, global names in a module and local names in the function invocation.

35.

Explain the importance of self in Python classes.

Answer»

self is an object reference to the object itself, therefore, they are same. Python methods are not called in the context of the object itself, self in Python may be used to deal with custom object models.

36.

What is the use of _init_ ? When is it called? Explain with an example.

Answer»

1. _init_ help to create objects and instances in the parent class.

2. It reserves the memory to the members of the class.

37.

What is the significance of super method? Give on example of the same.

Answer»

super ( ) function is used to call base class methods which have been extended in derived class.

Example :

class GradStudent (Student):

def_ init _(self) :

super (GradStudent, self). _init _( )

self. subject = ” ”

self. working = ” ”

def readGrad (self) :

# Call readStudent method of parent class super (GradStudent, self). 

readStudent ( )

38.

Explain LEGB rule.

Answer»

LEGB rule: when a name is encountered during the execution of the program, it searches for that name in the following order:

L. Local – It first makes a local search, i.e. in a current def statement.

E. Enclosing functions – It searches in all enclosing functions, from inner to outer.

G. Global (module) – It searches for global modules or for names declared global

B. Built-in (Python) – Finally it checks for any built-in functions in Python.

39.

Explain the usage of keyword ‘pass’ in class definition.

Answer»

When a class doesn’t define any methods or attributes, but syntactically, there needs to be something in the definition, so we use the pass. It is a statement that does nothing and is a good placeholder when you are stubbing out functions or classes.

40.

Is object of a class mutable? Why/why not?

Answer»

User classes are considered mutable. Python doesn’t have (absolutely) private attributes, so you can always change a class.

41.

Name the methods that can be used to:1. access attribute of an object2. delete an attribute of an object

Answer»

1. getattr(obj, name[, default])

2. delattr(obj, name)

42.

Predict the output of the following code snippet:ptr=50def result():global ptrptr=ptr+1print ptr result()print ptr

Answer»

The output is

51

51

43.

Give the statement to:1. Check whether the attribute str exists in the class Test whose object is T2. Assign a value “Hello” to the attribute str of class Test and object Tl.

Answer»

1. hasattr (Tl,str)

2. setattr (Tl, str, “Hello”)

44.

Predict the output of the following code:class Match:#“Runs and Wickets”runs=281wickets=5def init (self,runs, wickets) :self.runs=runsself.wickets=wicketsprint “Runs scored are :” ,runsprint “Wickets taken are :” .wicketsprint “Test. do :”, Match. docprint “Test._name_ , Match. _name_print “Test_module_ , Match.__module_print “Test. _bases_ , Match._bases_print “Test._dict_ , Match. _diet_

Answer»

Runs scored are : 281

Wickets taken are : 5

Test._ do_ : None

Test._name_ : Match

Test._module_ : main

Test._bases_ : ()

Test. _diet_ : {‘ _module _’: ‘_ main_ ’, ‘_doc _’: None, ‘runs’: 281, ‘_init_ ’:

<function _init_ at 0x0000000002DDFBA8>, ‘wickets’: 5}

45.

Write a class customer in Python Containing Deduct % Mark to be deducted if caldiscount () is following specifications. not invoked properly Instance attributes: inside input( ) function customernumber – numeric value No mark to be deducted if member function customemame – string value definitions are written inside the classprice, qty discount, totalprice, netprice – numeric value methods :init()-To assign initial values of customernumber as 111, customemame as “Leena”, qty as 0 and price, discount &amp; netprice as 0. caldiscount ( ) – To calculate discount, totalprice and netprice totalprice = price * qty discount is 25% of totalprice, if totalprice &gt;=50000discount 15% of totalprice, if totalprice &gt;=25000 and totalprice &lt;50000discount 10% of totalprice, if totalprice &lt;250000 netprice= totalprice – discountinput()-to read data members customer- name, customernumber, price, qty and call caldiscount() to calculate discount, totalprice and netprice.show( ) – to display Customer details.

Answer»

class customer:

def _init_(self):

self.customemumber=111

self.customemame=‘Leena’

self.qty=0

self.price=0

self.discount=0

self.netprice=0

def caldiscount(self):

totalprice = self.price*self.qty

if totalprice >= 50000:

self.discount=totalprice * 0.25

elif totalprice >= 25000:

self.discount = totalprice * 0.15 else:

self.discount = totalprice * 0.10

self.netprice = totalprice – self.discount

def input(self):

self.customernumber=input(“Enter Customer Number”)

self.customemame = raw_input(“Enter Customer Name”)

self.qty = input(“Enter Quantity”)

self.price = input(“Enter Price”)

self.caldiscount()

def show(self):

print “Customer Number”,

self.customernumber

print “Customer Name”,

self.customemame

print “Quantity”,self.quanti-ty

print “Price”,self.price

print “Discount”,self.discount

print “Net price”,self.netprice

c = customer()

c.inputO c.show()

46.

Define a class SUPPLY in Python with the following description: Private Members Code of type int FoodName of type string FoodType of type string Sticker of type string A member function GetType() to assign the following values for Food Type as per the given Sticker A function Foodln() to allow user to enter values for Code, EoodName, Sticker and call function GetType() to assign respective FoodType.StickerFood TypeGREENVegetarianYELLOWContains EggREDNon-VegetarianPUBLIC MEMBERSA function FoodOut() to allow user to view the contents of all the data members.

Answer»

class SUPPLY:

• constructor to create an object

def init (self) :

#constructor

self.FoodCode=()

self.FoodName=‘ ’

self.FoodType=‘ ’

self.Sticker=‘ ’

def Foodln(self):

self.FoodCode=input(“Enter Food Code”)

self.FoodName=raw_input(“Enter Food Name”)

self.Sticker=raw_input(“Enter Sticker Colour”)

def GetType(self):

if self.Sticker==‘GREEN’:

self.FoodType = ‘Vegetarian’

elif self.Sticker==’YELLOW’:

self.FoodType = ‘Contains Egg’

elif self.Sticker==‘RED’:

self.FoodType = ‘Non-Vegetarian’ else:

self.FoodType = ‘Not Known’

def FoodOut(self):

print “FoodCode’’,self.FoodCode

print “FoodName”,self.FoodName

print “FoodType”,self.FoodType

print “Sticker”,self.Sticker

S = SUPPLY()

S.FoodIn()

S.GetTÿpe()

S.FoodOut()

47.

Define a class ITEMINFO in Python with the following description:ICode (Item Code), Item (Item Name), Price (Price of each item), Qty (quantity in stock) Discount (Discount percentage on the item), Netprice (Final Price)Methods(i)  A member function FindDisc( ) to calculate discount as per the following rules:If Qty&lt; = 10Discount is 0If Qty (11 to 20)Discount is 15If Qty &gt; =20Discount is 20(ii) A constructor init method) to assign the value with 0 for ICode, Price, Qty, Netprice and Discountand null for Item respectively(iii) A function Buy( ) to allow user to enter values for ICode, Item, Price, Qty and call function FindDisc( )to calculate the discount and N etprice(Price * Qty-Discount).(iv) A Function ShowAll( ) to allow user to view the content of all the data members.

Answer»

class ITEMINFO:

#constructor to create an .object

def_init_(self):

#constructor

self.ICode=0

self.Item=‘ ’

self.Price=0.0

self.Qty=‘ ’

self.Discount=0

self.Netprice=0.0

def Buy(self):

self.ICode=input(“Enter Item Code”)

self. Item=raw_input(“Enter Item Name”)

self.Price=float(raw_input(“Enter Price”))

self.Qty=input(“Enter Quantity”)

def FindDisc(self):

if self.Qty <= 10:

self.Discount = 0

elif self.Qty >= 11 and self.Qty < 20 :

self.Discount = 15

else:

self.Discount = 20

self.Netprice= (self.Price*self.Qty)

self.Discount

def ShowAll(self):

print “Item Code’’,self.ICode

print “Item Name”,self.Item

print “Price”,self.Price

print “Quantity”,self.Qty

print “NetPrice”,self.Netprice

I = ITEMINFO()

I.Buy()

I.FindDisc()

I. Show All ()