How to use private method in Python

1 Answer

0 votes
class Account:
    def deposit(self, amount):
        self._log("Deposit")
        self.__update_balance(amount)

    def _log(self, action):
        print(f"Logging: {action}")

    def __update_balance(self, amount):
        print(f"Updating balance by {amount}")


acc = Account()

print("Calling deposit():")
acc.deposit(100) # OK

print("\nTrying to call _log() directly:")
acc._log("Manual log")   # Allowed, but discouraged

print("\nTrying to call __update_balance() directly:")
try:
    acc.__update_balance(200)  # Error
except AttributeError as e:
    print("Error:", e)

print("\nCalling name‑mangled private method:")
acc._Account__update_balance(200)  # Works, but intentionally ugly

  
'''
run:
  
ERROR!
Calling deposit():
Logging: Deposit
Updating balance by 100

Trying to call _log() directly:
Logging: Manual log

Trying to call __update_balance() directly:
Error: 'Account' object has no attribute '__update_balance'

Calling name‑mangled private method:
Updating balance by 200
  
'''

 



answered Jan 21 by avibootz

Related questions

1 answer 164 views
2 answers 206 views
1 answer 182 views
182 views asked Jan 1, 2017 by avibootz
1 answer 164 views
1 answer 189 views
...