Encapsulation Questions and Answers
Practice ModeShowing 10 of 25 questions
Q1
What is encapsulation in Python?
Answer: Option A
Explanation: Encapsulation is one of the fundamental principles of object-oriented programming that bundles data and methods together while restricting direct access to some components.
Q2
Which access modifier in Python indicates a protected member?
Answer: Option A
Explanation: In Python, single underscore (_) prefix indicates protected members, meaning they should not be accessed directly from outside the class.
Q3
What is the purpose of name mangling in Python?
Answer: Option A
Explanation: Name mangling with double underscore makes attributes harder to access directly from outside the class, providing a weak form of data hiding.
Q4
How do you create a private attribute in Python?
Answer: Option A
Explanation: Private attributes in Python are created using double underscore prefix, which triggers name mangling.
Q5
What are getter and setter methods used for in encapsulation?
Answer: Option A
Explanation: Getter and setter methods provide controlled access to private attributes, allowing validation and maintaining data integrity.
Q6
Which Python decorator is commonly used for getter methods?
Answer: Option A
Explanation: The @property decorator is used to define getter methods that can be accessed like attributes.
Q7
What is the main benefit of encapsulation?
Answer: Option A
Explanation: Encapsulation protects data integrity by preventing unauthorized access and modification of internal object state.
Q8
How can you access a private attribute named __salary from outside the class?
Answer: Option A
Explanation: Private attributes can still be accessed using name mangling format: _ClassName__attributeName
Q9
What does the @attribute.setter decorator do?
Answer: Option A
Explanation: The @attribute.setter decorator defines a setter method for a property, allowing controlled modification of the attribute.
Q10
Which of the following is true about Python encapsulation?
Answer: Option A
Explanation: Python encapsulation is more about convention than enforcement, as private members can still be accessed with name mangling.