Lesson 2 of 7 · Classes and Objects · 3 min read · Updated

Methods and attributes

Methods that change an object, values shared by every object, and class and static methods.

python
class BankAccount:
    bank = "City Co-op Bank"   # shared by every account
    count = 0

    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance
        BankAccount.count += 1

    def deposit(self, amount):
        self.balance += amount
        return self.balance

    def withdraw(self, amount):
        if amount > self.balance:
            raise ValueError("Insufficient balance")
        self.balance -= amount
        return self.balance

a = BankAccount("Kavya", 1000)
b = BankAccount("Ravi")
print(a.deposit(500))
print(a.withdraw(200))
print(b.balance, b.bank)
print(BankAccount.count)
Output
1500
1300
0 City Co-op Bank
2
  • Instance attributes (self.balance) belong to one object. Kavya's deposit did not touch Ravi's balance.
  • Class attributes (bank, count) are written in the class body and shared by all objects.
  • Methods keep the rules in one place: nobody can withdraw more than the balance, because withdraw() checks.

Warning

Update a shared counter through the class — BankAccount.count += 1. Writing self.count += 1 quietly creates a separate instance attribute on that one object, and the shared count never changes.

Class methods and static methods

python
class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    @classmethod
    def from_fahrenheit(cls, f):
        return cls((f - 32) * 5 / 9)

    @staticmethod
    def is_fever(celsius):
        return celsius > 37.5

t = Temperature.from_fahrenheit(212)
print(t.celsius)
print(Temperature.is_fever(38.2))
Output
100.0
True

A @classmethod receives the class (cls) instead of an object — the usual use is an alternative way to create objects. A @staticmethod receives neither; it is a plain function kept in the class because it belongs with it.

Two accounts are created. Where should a count of all accounts be stored?

Try this now

  1. Add a transfer(other, amount) method to BankAccount that withdraws from one account and deposits into another.
  2. Add a @classmethod from_string("Kavya,1000") that builds an account from text.

Create a free account to save your progress, or sign in.