Methods & Attributes
Attributes are the data an object holds, and methods are the actions it can perform. Knowing the difference between instance and class attributes, and between instance, class and static methods, helps you design clean, bug-free classes.
Instance attributes and class attributes
- Instance attributes belong to one object. You usually create them in
__init__withself.name = .... - Class attributes are defined directly in the class body and are shared by all objects of that class.
class BankAccount:
bank_name = "Umoja SACCO" # class attribute: same for everyone
interest_rate = 0.05
accounts_opened = 0
def __init__(self, owner, balance=0):
self.owner = owner # instance attributes: different for each account
self.balance = balance
BankAccount.accounts_opened += 1
def deposit(self, amount):
self.balance += amount
return self.balance
def add_interest(self):
self.balance += self.balance * self.interest_rate
halima = BankAccount("Halima", 1000)
print(halima.deposit(500))
halima.add_interest()
print(halima.balance)
print(halima.bank_name, BankAccount.accounts_opened)
When you read self.interest_rate, Python first looks on the object. It doesn't find it there, so it looks on the class and uses 0.05. To change a shared counter, update it through the class name, as in BankAccount.accounts_opened += 1.
Assigning to a class attribute through an object doesn't change the class. It quietly creates a new instance attribute that hides the shared one:
kevin = BankAccount("Kevin", 2000)
kevin.interest_rate = 0.10 # only Kevin's account
print(kevin.interest_rate, halima.interest_rate, BankAccount.interest_rate)
Also avoid mutable class attributes such as members = []: every object would append to the same list. Create lists in __init__ instead.
Instance methods
Most methods are instance methods: their first parameter is self, so they can read and change that object's attributes. Methods can take extra arguments, return values and call other methods with self.method().
class Wallet:
def __init__(self, owner):
self.owner = owner
self.balance = 0
self.history = []
def receive(self, amount, sender):
self.balance += amount
self.history.append(f"+{amount} from {sender}")
def send(self, amount, recipient):
if amount > self.balance:
return False
self.balance -= amount
self.history.append(f"-{amount} to {recipient}")
return True
def statement(self):
lines = [f"{self.owner}'s wallet: KES {self.balance}"]
lines.extend(self.history)
return "\n".join(lines)
w = Wallet("Imani")
w.receive(3000, "Mum")
print(w.send(1200, "Landlord"))
print(w.send(5000, "Shop"))
print(w.statement())
Class methods and static methods
@classmethod
A class method receives the class (by convention called cls) instead of an object. Its most common use is as an alternative constructor: another way to create objects.
@staticmethod
A static method receives neither the object nor the class. It's just a regular function that lives inside the class because it's related to it.
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
@classmethod
def from_string(cls, text):
owner, balance = text.split(",")
return cls(owner.strip(), int(balance))
@staticmethod
def is_valid_amount(amount):
return amount > 0
acc = BankAccount.from_string("Kevin, 2000")
print(acc.owner, acc.balance)
print(BankAccount.is_valid_amount(-50))
print(BankAccount.is_valid_amount(250))
| Kind | First parameter | Can use | Typical use |
|---|---|---|---|
| Instance method | self | The object and its class | Most behaviour: deposit, withdraw |
@classmethod | cls | The class | Alternative constructors, class-wide settings |
@staticmethod | None | Only its arguments | Helper functions related to the class |
Inspecting and changing attributes dynamically
Python lets you look at an object's attributes and access them by name, which is useful for debugging or when attribute names come from data.
acc = BankAccount("Amani", 750)
print(vars(acc)) # the object's own attributes
print(hasattr(acc, "balance"))
print(getattr(acc, "owner"))
print(getattr(acc, "branch", "not set")) # default if missing
setattr(acc, "branch", "Kisii")
print(acc.branch)
Forgetting self. inside a method. Writing balance += amount instead of self.balance += amount refers to a local variable that doesn't exist and raises UnboundLocalError. Inside methods, always reach object data through self.
Sometimes you'll want to control how attributes are read and changed, for example to stop a balance going negative. That's encapsulation.
Key points
- Instance attributes belong to one object; class attributes are shared.
- Change shared values through the class name, not through an object.
- Instance methods use
self; class methods usecls; static methods use neither. vars(),hasattr(),getattr()andsetattr()work with attributes by name.
Tip: use the ← and → keys to move between pages.
