codegurukool.com · Free coding tutorials & online compiler

Home › Python Tutorial › Python encapsulation and magic methods

Python encapsulation and magic methods

Hide details and customise behaviour.

A name starting with two underscores (__balance) is private to the class. Magic methods such as __str__ control how an object prints.

Example code

class Account:
    def __init__(self, balance):
        self.__balance = balance

    def deposit(self, n):
        self.__balance += n

    def __str__(self):
        return f"Balance: {self.__balance}"

a = Account(100)
a.deposit(50)
print(a)

Run this code in the online editor

← Python inheritance and polymorphismPython file handling →