Python Programming - Classes

Exercise : Classes - General Questions
  • Classes - General Questions
1.
What is the purpose of the __init__ method in a Python class?
It is used to initialize the class variables.
It is a reserved method for object initialization.
It defines the constructor of the class.
It is required for defining instance methods.
Answer: Option
Explanation:
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.

2.
In Python, what does the term self refer to in a class method?
It represents the instance of the class.
It refers to the superclass object.
It is a keyword for defining class variables.
It is used for static method declaration.
Answer: Option
Explanation:
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.

3.
How can you create a class variable?
Define it inside a method with the keyword var.
Declare it outside any method in the class with the keyword static.
Use the self keyword inside a method.
Define it inside the constructor using __init__.
Answer: Option
Explanation:
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.

4.
What is the purpose of the __str__ method?
It converts an object to a string representation.
It is used to define a string variable in a class.
It represents the string type in Python.
It is required for string concatenation.
Answer: Option
Explanation:
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.

5.
How can you inherit a class?
Using the inherit keyword.
By using the extends keyword.
Using the inherits keyword.
By placing the parent class name in parentheses after the child class name.
Answer: Option
Explanation:
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.