Code Explanation:
1. Class Definition
class Account:
This line defines a class named Account.
2. Constructor Method (__init__)
def __init__(self):
self.__balance = 500
__init__ is a constructor, automatically called when an object is created.
self.__balance is a private variable.
Python applies name mangling to variables that start with __.
Internally, __balance becomes:
_Account__balance
The value 500 is assigned to this private variable.
3. Object Creation
acc = Account()
An object named acc is created from the Account class.
The constructor runs, setting the private balance to 500.
4. Accessing Private Variable Using Name Mangling
print(acc._Account__balance)
Direct access like acc.__balance is not allowed.
Python allows access using name-mangled form:
object._ClassName__variableName
Here:
Class name → Account
Variable name → __balance
So:
acc._Account__balance
This prints the value stored in __balance.
5. Output
500


0 Comments:
Post a Comment