Course topics

By WebNest Studio

Python Tutorial

Classes and Objects in Python

Object-oriented programming (OOP) organises code around objects that bundle data (attributes) and behaviour (methods). A class is the blueprint; an object (or instance) is a concrete thing built from it. A BankAccount class describes what every account has and can do; each customer's account is an object.

This lesson covers defining classes, creating objects, instance attributes and methods, the self parameter, class attributes, and how objects are identified and compared.

Defining a Class and Creating Objects

Use the class keyword and PascalCase names. Calling the class like a function — Account("Asha") — creates a new object, runs its __init__ method, and returns the object. Each object has its own attributes, stored in its __dict__.

self and Methods

A method is a function defined inside a class. Its first parameter, conventionally named self, is the object the method was called on: account.deposit(500) is really Account.deposit(account, 500). Through self, methods read and change the object's attributes.

Class Attributes vs Instance Attributes

Attributes assigned on self belong to one object. Attributes assigned in the class body are shared by all instances — useful for constants and counters. Reading obj.attr looks in the instance first, then the class. Assigning obj.attr = ... always creates an instance attribute, which can shadow the class attribute.

Identity, Equality and Printing

Two separate objects with the same data are not the same object: is compares identity, and by default == does too — until you define __eq__. Printing an object shows something like <__main__.Account object at 0x...> until you define __str__ or __repr__ (see the magic methods lesson).

Examples

A class with attributes and methods

Python
class BankAccount:
    bank_name = "Webnest Bank"          # class attribute (shared)

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

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

    def withdraw(self, amount):
        if amount > self.balance:
            print(f"Insufficient funds for {self.owner}")
            return self.balance
        self.balance -= amount
        return self.balance


asha = BankAccount("Asha", 1000)
ravi = BankAccount("Ravi")
asha.deposit(500)
asha.withdraw(200)
ravi.withdraw(50)
print(asha.owner, asha.balance, "|", ravi.owner, ravi.balance)
print(asha.bank_name, BankAccount.bank_name)
print(asha.__dict__)
Output
Insufficient funds for Ravi
Asha 1300 | Ravi 0
Webnest Bank Webnest Bank
{'owner': 'Asha', 'balance': 1300}

self is just the object: method call equivalence

Python
class Greeter:
    def __init__(self, name):
        self.name = name

    def greet(self, greeting):
        return f"{greeting}, {self.name}!"

g = Greeter("Meera")
print(g.greet("Hello"))
print(Greeter.greet(g, "Namaste"))     # the same call, spelled out
Output
Hello, Meera!
Namaste, Meera!

Class attributes as shared state, and shadowing

Python
class Student:
    school = "Webnest Academy"
    count = 0

    def __init__(self, name):
        self.name = name
        Student.count += 1

a, b = Student("Asha"), Student("Ravi")
print(Student.count, a.school)

b.school = "Other School"        # creates an instance attribute on b only
print(a.school, "|", b.school, "|", Student.school)
print("school" in vars(a), "school" in vars(b))
Output
2 Webnest Academy
Webnest Academy | Other School | Webnest Academy
False True

Identity and equality of objects

Python
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

p1, p2 = Point(1, 2), Point(1, 2)
p3 = p1
print(p1 is p2, p1 == p2, p1 is p3)
print(isinstance(p1, Point), type(p1).__name__)
Output
False False True
True Point

Common Mistakes

  • Forgetting self as the first method parameter (TypeError: takes 0 positional arguments but 1 was given).
  • Using a mutable class attribute (items = []) that every instance accidentally shares.
  • Writing count += 1 on self instead of the class, creating an instance attribute.
  • Expecting == to compare object contents without defining __eq__.

Key Points to Remember

  • A class is a blueprint; calling it creates an object and runs __init__.
  • Methods receive the object as self; attributes set on self belong to that object.
  • Class attributes are shared; instance attributes shadow them.
  • is compares identity; == compares identity too unless __eq__ is defined.

Practice the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.