Test Series - python

Test Number 103/108

Q: _____ represents an entity in the real world with its identity and behaviour.
A. A method
B. An object
C. A class
D. An operator
Solution: An object represents an entity in the real world that can be distinctly identified. A class may define an object.
Q: _____ is used to create an object.
A. class
B. constructor
C. User-defined functions
D. In-built functions
Solution: The values assigned by the constructor to the class members is used to create the object.
Q: What will be the output of the following Python code?

class test:
     def __init__(self,a="Hello World"):
         self.a=a
 
     def display(self):
         print(self.a)
obj=test()
obj.display()
A. The program has an error because constructor can’t have default arguments
B. Nothing is displayed
C. “Hello World” is displayed
D. The program has an error display function doesn’t have parameters
Solution: The program has no error. “Hello World” is displayed. Execute in python shell to verify.
Q: What is setattr() used for?
A. To access the attribute of the object
B. To set an attribute
C. To check if an attribute exists or not
D. To delete an attribute
Solution: setattr(obj,name,value) is used to set an attribute. If attribute doesn’t exist, then it would be created.
Q: What is getattr() used for?
A. To access the attribute of the object
B. To delete an attribute
C. To check if an attribute exists or not
D. To set an attribute
Solution: getattr(obj,name) is used to get the attribute of an object.
Q: What will be the output of the following Python code?

 class test:
     def __init__(self,a):
         self.a=a
 
     def display(self):
         print(self.a)
obj=test()
obj.display()
A. Runs normally, doesn’t display anything
B. Displays 0, which is the automatic default value
C. Error as one argument is required while creating the object
D. Error as display function requires additional argument
Solution: Since, the __init__ special method has another argument a other than self, during object creation, one argument is required. For example: obj=test(“Hello”)
Q: Is the following Python code correct?

>>> class A:
	def __init__(self,b):
		self.b=b
	def display(self):
		print(self.b)
>>> obj=A("Hello")
>>> del obj
A. True
B. False
C. none
D. ...
Solution: It is possible to delete an object of the class. On further typing obj in the python shell, it throws an error because the defined object has now been deleted.
Q: What is Instantiation in terms of OOP terminology?
A. Deleting an instance of class
B. Modifying an instance of class
C. Copying an instance of class
D. Creating an instance of class
Solution: Instantiation refers to creating an object/instance for a class.

You Have Score    /8