Python - Encapsulation and Data ProtectionWhich of the following is the correct way to define a private attribute using name mangling in a Python class?Aself.__my_attr = 5Bdef __my_attr(self): passCself._my_attr = 5Dself.my_attr__ = 5Check Answer
Step-by-Step SolutionSolution:Step 1: Identify private attribute syntaxPrivate attributes use double underscores at the start of the name, like __my_attr.Step 2: Check correct assignmentAssigning with self.__my_attr = 5 correctly defines a private attribute with name mangling.Final Answer:self.__my_attr = 5 -> Option AQuick Check:Double underscore prefix = private attribute [OK]Quick Trick: Use double underscores before attribute name for private [OK]Common Mistakes:Using single underscore instead of doublePlacing underscores after attribute nameDefining private attribute as a method incorrectly
Master "Encapsulation and Data Protection" in Python9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallTime
More Python Quizzes Classes and Object Lifecycle - Instance attributes - Quiz 4medium Classes and Object Lifecycle - Creating objects - Quiz 9hard Classes and Object Lifecycle - Class definition syntax - Quiz 13medium Constructors and Object Initialization - Self reference - Quiz 15hard Context Managers - Automatic resource cleanup - Quiz 10hard Context Managers - With statement execution flow - Quiz 15hard Encapsulation and Data Protection - Getter and setter methods - Quiz 10hard Exception Handling Fundamentals - Generic exception handling - Quiz 11easy File Reading and Writing Strategies - Overwrite vs append behavior - Quiz 4medium Methods and Behavior Definition - Modifying object state - Quiz 4medium