Python Classes & Objects
In this page:
Creating a Class
You define a class with the class keyword followed by a PascalCase name (like class BankAccount:), and if you're not ready to fill in the body yet, the pass statement is a valid placeholder that lets the file still run without a syntax error.
Example: Creating a Class
class BankAccount:
pass
print(BankAccount)
Instantiating Objects
Calling the class name like a function -- BankAccount() -- creates a new object from that blueprint; this triggers the class's __init__ method automatically, which is where you'd typically set up that object's starting attribute values.
Example: Instantiating Objects
class BankAccount:
def __init__(self):
print("Account created")
account = BankAccount()
Class vs Instance Attributes
A class attribute is defined directly inside the class body and shared by every instance (changing it affects all objects at once), while an instance attribute is set inside a method (usually __init__) via self.x and belongs to just that one object.
Example: Class vs Instance Attributes
class BankAccount:
bank_name = "Cursor Bank" # class attribute
def __init__(self, owner):
self.owner = owner # instance attribute
a = BankAccount("Alex")
print(a.bank_name, a.owner)
Class Methods
Every method defined inside a class automatically receives the calling object as its first argument, conventionally named self -- that's how a method like deposit() knows which specific account's balance to update rather than a shared or ambiguous one.
Example: Class Methods
class BankAccount:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance += amount
a = BankAccount(100)
a.deposit(50)
print(a.balance)
Modifying Object Properties
You can read or reassign an object's attribute directly from outside the class using dot notation (account.balance = 500), though relying on getter/setter methods or @property is often safer once you need validation on that assignment.
Example: Modifying Object Properties
class BankAccount:
def __init__(self, balance):
self.balance = balance
a = BankAccount(100)
a.balance = 500
print(a.balance)
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: