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:MISTAKESUsing 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 Constructors and Object Initialization - __init__ method behavior - Quiz 4medium File Handling Fundamentals - Reading file data - Quiz 8hard Methods and Behavior Definition - Modifying object state - Quiz 4medium Modules and Code Organization - Importing specific items - Quiz 11easy Object-Oriented Programming Foundations - Procedural vs object-oriented approach - Quiz 13medium Object-Oriented Programming Foundations - Why object-oriented programming is used - Quiz 14medium Polymorphism and Dynamic Behavior - Polymorphism through functions - Quiz 11easy Polymorphism and Dynamic Behavior - Polymorphism through functions - Quiz 12easy Structured Data Files - Working with JSON files - Quiz 11easy Structured Data Files - Why structured data formats are used - Quiz 5medium