By WebNest Studio Engineering Team
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.
Why it matters
The difference between an attribute that belongs to the class and one that belongs to a single object is small in the code and large in its effect. Getting it wrong leads to data that is shared between objects when it should not be. This lesson is the foundation for every other topic in object-oriented Python.
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
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__)
Insufficient funds for Ravi
Asha 1300 | Ravi 0
Webnest Bank Webnest Bank
{'owner': 'Asha', 'balance': 1300}
self is just the object: method call equivalence
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
Hello, Meera!
Namaste, Meera!
Class attributes as shared state, and shadowing
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))
2 Webnest Academy
Webnest Academy | Other School | Webnest Academy
False True
Identity and equality of objects
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__)
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__.
Exercise
Write a Student class with a class attribute school set to WebNest and a class attribute count that increases each time a student is created. Then observe what happens when school is assigned through one object.
Expected output: 2, Other, WebNest (one per line)
class Student:
# TODO: class attributes school and count
# TODO: __init__ that stores the name and increases the shared count
pass
first = Student("Asha")
second = Student("Ravi")
print(Student.count)
first.school = "Other"
print(first.school)
print(second.school)
Show hints
- Class attributes are assigned directly in the class body, outside any method.
- Increase the shared counter with
Student.count += 1. Writingself.count += 1would create a separate attribute on the object.
Show solution
class Student:
school = "WebNest"
count = 0
def __init__(self, name):
self.name = name
Student.count += 1
first = Student("Asha")
second = Student("Ravi")
print(Student.count)
first.school = "Other"
print(first.school)
print(second.school)
Quick quiz
1. Where is a class attribute stored?
- A. In every object separately
- B. In the module
- C. On the class, and shared by all its objects
- D. In __init__
Show answer
C. Objects read it through the class unless they have an attribute of their own with the same name.
2. Two objects of a class that defines no __eq__ hold the same values. What does a == b return?
- A. True
- B. False
- C. It raises an error
- D. None
Show answer
B. Without __eq__, equality falls back to identity, and they are two different objects.
3. Which call is equivalent to account.deposit(100)?
- A. Account.deposit(account, 100)
- B. deposit(account, 100)
- C. Account(deposit, 100)
- D. account.Account.deposit(100)
Show answer
A. The object before the dot is passed as the first argument, self.
Interview questions
What is the difference between a class attribute and an instance attribute?
Show answer
A class attribute is defined in the class body and there is one copy, shared by every object. An instance attribute is assigned through self, usually in __init__, and each object has its own. Reading an attribute looks on the object first and then on the class. Assigning through an object always creates or changes an instance attribute, which then hides the class attribute for that object only.
Why is a mutable class attribute dangerous?
Show answer
A list or dictionary defined in the class body is a single object shared by all instances. If one instance appends to it, every instance sees the new item, which is rarely intended. Data that should belong to each object must be created in __init__, as in self.items = [].
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 in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering