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:
| Parameter | Type | Description |
|---|---|---|
| self | Instance Reference | Refers to the specific object instance calling the method. |
| __init__ | Constructor Method | Initializes state when a new object is created. |
Ready-to-Run Code Example
Executable in CompilraRun 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
Python Inheritance, Polymorphism, and the super() Function
Inheritance allows a class to derive features from a parent class, promoting code reuse and polymorphic behavior.
Python Functions (def): Arguments, *args, **kwargs & Return
Functions are organized, reusable blocks of code defined using the def keyword to perform a specific action.
Python Exception Handling: try, except, else, and finally
Exceptions in Python are handled gracefully using try...except blocks to catch runtime errors without crashing.
Python Online Compiler
Open in Compilra IDE
Run and test Python on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.