Skip to content
Kuza Ndoto Academy

Methods & Attributes

Beginner → IntermediateChapter 8 · Page 42 of 564 min readUpdated 15 Nov 2026

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__ with self.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)
1500 1575.0 Umoja SACCO 1

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.

halima (object) instance attributes (data) owner = "Halima" balance = 1575.0 falls back to BankAccount (class) class attributes (shared data) bank_name = "Umoja SACCO" interest_rate = 0.05 methods (behaviour) deposit(amount) add_interest()
Figure 1. Anatomy of an object: its own data lives on the object, while shared data and behaviour live on the class. When a name isn't found on the object, Python looks on the class.
Common mistake

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)
0.1 0.05 0.05

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())
True False Imani's wallet: KES 1800 +3000 from Mum -1200 to Landlord

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))
Kevin 2000 False True
KindFirst parameterCan useTypical use
Instance methodselfThe object and its classMost behaviour: deposit, withdraw
@classmethodclsThe classAlternative constructors, class-wide settings
@staticmethodNoneOnly its argumentsHelper 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)
{'owner': 'Amani', 'balance': 750} True Amani not set Kisii
Common mistake

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 use cls; static methods use neither.
  • vars(), hasattr(), getattr() and setattr() work with attributes by name.
Up next · Object-Oriented PythonInheritanceBuild new classes from existing ones.
→

Tip: use the ← and → keys to move between pages.