Exercise: Classes
Questions for: Classes
How can you inherit a class?
A:
Using the
inherit keyword.
B:
By using the
extends keyword.
C:
Using the
inherits keyword.
D:
By placing the parent class name in parentheses after the child class name.
Answer: D
In Python, class inheritance is achieved by placing the name of the parent class in parentheses after the name of the child class. This creates a relationship where the child class inherits attributes and methods from the parent class.
What is the purpose of the
__str__ method?
A:
It converts an object to a string representation.
B:
It is used to define a string variable in a class.
C:
It represents the string type in Python.
D:
It is required for string concatenation.
Answer: A
The
__str__ method is called when the str() function is used on an object. It is used to provide a human-readable string representation of the object.Discuss About this Question.
How can you create a class variable?
A:
Define it inside a method with the keyword
var.
B:
Declare it outside any method in the class with the keyword
static.
C:
Use the
self keyword inside a method.
D:
Define it inside the constructor using
__init__.
Answer: B
Class variables in Python are declared outside any method in the class and are shared by all instances of the class. They are typically defined with the
static keyword.Discuss About this Question.
In Python, what does the term
self refer to in a class method?
A:
It represents the instance of the class.
B:
It refers to the superclass object.
C:
It is a keyword for defining class variables.
D:
It is used for static method declaration.
Answer: A
In Python, the term
self is a convention used to represent the instance of the class. It is the first parameter in the method definition and refers to the instance on which the method is called.Discuss About this Question.
What is the purpose of the
__init__ method in a Python class?
A:
It is used to initialize the class variables.
B:
It is a reserved method for object initialization.
C:
It defines the constructor of the class.
D:
It is required for defining instance methods.
Answer: B
The
__init__ method is a special method in Python classes that is automatically called when an object is created. It is used to initialize the object's attributes or perform any other setup needed for the object.Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.