Skip to main content

Classes and Objects

A class is a blueprint; an object is an instance of it.

classes.py
class Account:
bank = "PrepVerse Bank" # class attribute

def __init__(self, owner, balance=0):
self.owner = owner # instance attributes
self._balance = balance

def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
self._balance += amount

@property
def balance(self):
return self._balance

def __repr__(self):
return f"Account({self.owner!r}, {self._balance})"


acct = Account("Asha", 100)
acct.deposit(50)
print(acct.balance) # 150
print(acct) # Account('Asha', 150)

Key ideas​

  • __init__ initialises a new instance; self is the instance.
  • A leading underscore (_balance) is a convention for "internal".
  • @property exposes a computed or read-only attribute.
  • @classmethod receives the class, @staticmethod receives neither.
methods.py
class Temperature:
def __init__(self, celsius):
self.celsius = celsius

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

@staticmethod
def is_valid(c):
return c >= -273.15