Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Implement a Private Attribute in a ClassE02. Add Getter and Setter Methods for an AttributeE03. Convert Attribute Access to a PropertyE

Problem No 2

Add Getter and Setter Methods for an Attribute

Easy

9 minute session

Summary

Implement getter and setter methods with simple validation for a private attribute.

Problem statement

Implement a BankAccount class that stores the balance in a private attribute (name-mangled). Provide a get_balance() method that returns the current balance and a set_balance(amount) method that updates the balance only if amount is an integer >= 0. If the update is valid, set_balance should update the private attribute and return self so calls can be chained; if invalid, it should not change the balance and should return None. This exercise teaches controlled access and validation through explicit getter and setter methods.

Task

Create getter and setter methods for a private attribute. The setter should validate input and only update when valid, returning the instance on success and None on failure.

Examples

Create account and set balance

Input

BankAccount(100).set_balance(250).get_balance()

Output

250

Explanation

set_balance updates the private balance and returns the instance so get_balance can be chained.

Input format

A single expression that creates a BankAccount and calls get_balance()/set_balance() (evaluated by the test runner).

Output format

Return numeric balance from get_balance(); set_balance returns the instance on success (so chaining returns a balance) or None on failure (represented as an empty string by the test harness).

Constraints

Balance must be an integer >= 0. Use a private (double-underscore) attribute to store the balance. set_balance should return self on success and None on invalid input.

Samples

Sample input 0

BankAccount(100).get_balance()

Sample output 0

100

Explanation 0

Initial balance is returned by get_balance.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

03:46 PM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.