Back to course

Instance Methods and Modifying Attributes

Python Programming: The 0 to Hero Bootcamp

Working with Instance Methods

Instance methods are functions defined within a class that operate on the specific data of an object (instance).

Accessing and Modifying self

Methods use the self reference to read or change the object's attributes.

python class Account: def init(self, owner, balance): self.owner = owner self.balance = balance

def deposit(self, amount):
    self.balance += amount
    print(f"Deposited ${amount}. New balance: ${self.balance}")
    
def withdraw(self, amount):
    if amount > self.balance:
        print("Transaction failed: Insufficient funds.")
        return False
    
    self.balance -= amount
    print(f"Withdrew ${amount}. Remaining balance: ${self.balance}")
    return True

Use the class

my_account = Account('Smith', 500)

my_account.deposit(200) # Balance is now 700 my_account.withdraw(100) # Balance is now 600 my_account.withdraw(1000) # Fails