Skip to content
  • Classes & Objects · Python

Classes & Objects

LearnViaNotes @learnvianotes· 2 min read

A class bundles data (attributes) and behaviour (methods). In Python everything — even functions and classes themselves — is an object.

Anatomy of a class

Python
class Account:
    bank = "LVN Bank"                   # class attribute: shared by all instances

    def __init__(self, owner, balance=0):
        self.owner = owner              # instance attributes: one per object
        self.balance = balance

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

a = Account("Asha")
b = Account("Ravi", 100)
a.deposit(50)
print(a.balance, b.balance, a.bank)     # 50 100 LVN Bank

Three kinds of methods

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

    def to_f(self):                      # instance method: gets self
        return self.celsius * 9 / 5 + 32

    @classmethod
    def from_f(cls, f):                  # class method: gets the class → alternative constructors
        return cls((f - 32) * 5 / 9)

    @staticmethod
    def is_freezing(c):                  # static method: a plain function in the class namespace
        return c <= 0

t = Temperature.from_f(212)
print(t.celsius, t.to_f(), Temperature.is_freezing(-3))   # 100.0 212.0 True

Properties: attributes with logic

Python
class Circle:
    def __init__(self, radius):
        self.radius = radius             # goes through the setter below

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, value):
        if value < 0:
            raise ValueError("radius must be >= 0")
        self._radius = value

    @property
    def area(self):                      # computed, read-only
        return round(3.14159 * self._radius ** 2, 2)

c = Circle(2)
print(c.area)                            # 12.57
try:
    c.radius = -1
except ValueError as e:
    print(e)                             # radius must be >= 0

Encapsulation by convention

NameMeaning
namePublic API
_nameInternal — “please don't touch” (not enforced)
__nameName-mangled to _ClassName__name to avoid clashes in subclasses
__name__Special (dunder) names reserved for Python

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report