Python:Python Classes and Objects (OOP): __init__, Methods & self
Python•OOP Basics

Python Classes and Objects (OOP): __init__, Methods & self

Object-Oriented Programming (OOP) in Python models real-world systems through classes, attributes, methods, and constructor initialization (__init__).

Syntax

class ClassName: def __init__(self, attribute): self.attribute = attribute def method(self): # instance method

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
selfInstance ReferenceRefers to the specific object instance calling the method.
__init__Constructor MethodInitializes state when a new object is created.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Python locally:

# Python OOP: BankAccount Class
class BankAccount:
    """Represents a checking/savings account with balance validation."""
    def __init__(self, account_holder: str, initial_deposit: float = 0.0):
        self.holder = account_holder
        self.balance = initial_deposit

    def deposit(self, amount: float) -> float:
        if amount > 0:
            self.balance += amount
            print(f"Deposited ${amount:.2f}. New Balance: ${self.balance:.2f}")
        return self.balance

    def withdraw(self, amount: float) -> bool:
        if 0 < amount <= self.balance:
            self.balance -= amount
            print(f"Withdrew ${amount:.2f}. Remaining: ${self.balance:.2f}")
            return True
        print(f"Withdrawal failed: insufficient funds for ${amount:.2f}!")
        return False

# Create instance and test methods
account = BankAccount("Sarah Conner", 500.0)
account.deposit(250.0)
account.withdraw(100.0)
account.withdraw(900.0)
Expected Output:
Deposited $250.00. New Balance: $750.00
Withdrew $100.00. Remaining: $650.00
Withdrawal failed: insufficient funds for $900.00!

How It Works: Step-by-Step

  • Lines 4-6: __init__ binds initial account holder name and balance to self.
  • Lines 8-12: deposit() method updates self.balance and prints transaction status.
  • Lines 14-20: withdraw() guards against overdraft and subtracts valid funds.

Key Concepts

  • self must be the first parameter in instance methods to bind to the calling object.
  • __init__() runs automatically whenever you instantiate ClassName().
  • Attributes set on self are instance-specific and isolated from other instances.

Common Mistake: Omitting self as the first parameter in class methods

Python automatically passes the instance as the first argument to instance methods.

❌ Incorrect
class User:
    def greet(): # TypeError: greet() takes 0 positional arguments but 1 was given
        print("Hi")
✅ Correct
class User:
    def greet(self):
        print("Hi")

Related Python Tutorials & Compiler

Run and test Python on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Python Online Compiler