Complete the code to declare a private attribute in a class.
class User: def __init__(self, name): self.[1]name = name
In Python, prefixing an attribute with double underscores __ makes it private by name mangling, which helps encapsulate the data.
Complete the code to provide controlled access to a private attribute using a getter method.
class Account: def __init__(self, balance): self.__balance = balance def get_[1](self): return self.__balance
The getter method is conventionally named after the attribute it accesses, here balance.
Fix the error in the setter method to update the private attribute safely.
class Employee: def __init__(self, salary): self.__salary = salary def set_salary(self, amount): if amount > 0: self.[1]salary = amount
The setter must update the private attribute with the double underscore prefix to maintain encapsulation.
Fill both blanks to implement a property decorator for controlled access to a private attribute.
class Product: def __init__(self, price): self.__price = price @property def [1](self): return self.__price @[2].setter def price(self, value): if value >= 0: self.__price = value
@property decorator on the getter.The property and its setter must share the same name to work correctly, here price.
Fill all three blanks to implement encapsulation with private attribute, getter, and setter using property decorators.
class BankAccount: def __init__(self, balance): self.[1]balance = balance @property def [2](self): return self.__balance @[3].setter def balance(self, amount): if amount >= 0: self.__balance = amount
The private attribute uses double underscores __. The property and setter share the name balance for controlled access.