A class is a blueprint, and an object is a thing built from it. A Student class describes what every student has (a name, marks) and can do (work out a grade); each actual student is an object with its own values. Classes let you keep data and the functions that work on it together, which is the core idea of object-oriented programming (OOP).
In this lesson you will learn
- How to define a class and create objects from it
- What
__init__andselfdo - The difference between instance and class attributes
- How to write methods, including
__str__ - How objects keep their own separate state
Your First Class
class Student:
school = "Core Tech ED" # class attribute, shared by all
def __init__(self, name, marks):
self.name = name # instance attributes
self.marks = marks
def grade(self):
if self.marks >= 80:
return "A"
if self.marks >= 60:
return "B"
return "C"
def __str__(self):
return f"{self.name} ({self.marks})"
s1 = Student("Rafi", 85)
s2 = Student("Nila", 64)
print(s1.name, s1.grade())
print(s2, s2.grade())
print(s1.school, s2.school)
print(isinstance(s1, Student))
Output
Rafi A
Nila (64) B
Core Tech ED Core Tech ED
True
class Student:defines the blueprint. By convention, class names use CapitalisedWords.__init__runs automatically when you create an object withStudent("Rafi", 85). It sets up the object’s starting values.selfis the object being worked on.self.name = namestores the name on that object. Python passesselffor you; you never write it in the call.- Instance attributes (
name,marks) belong to one object. The class attributeschoolis shared by every object. __str__controls whatprint(obj)shows. Without it you would see something like<Student object at 0x...>.
Objects Keep Their Own State
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
self.history = []
def deposit(self, amount):
self.balance += amount
self.history.append(("deposit", amount))
return self # allows chaining
def withdraw(self, amount):
if amount > self.balance:
print("Not enough balance")
return self
self.balance -= amount
self.history.append(("withdraw", amount))
return self
acc = BankAccount("Tania", 500)
acc.deposit(200).withdraw(100).withdraw(900)
print(acc.balance)
print(acc.history)
other = BankAccount("Arif")
print(other.balance, len(other.history))
Output
Not enough balance
600
[('deposit', 200), ('withdraw', 100)]
0 0
Each account has its own balance and history. Changing Tania’s account does not touch Arif’s. The methods return self, so calls can be chained on one line. The failed withdrawal of 900 printed a message and left the balance unchanged.
Do not use a list as a class attribute for per-object data
If history = [] were written at class level, every account would share the same list. Create mutable values inside __init__ so each object gets its own.
Key OOP Terms
| Term | Meaning |
|---|---|
| Class | The blueprint: class BankAccount: |
| Object / instance | One thing made from the class: acc = BankAccount("Tania") |
| Attribute | Data stored on an object: acc.balance |
| Method | A function defined in the class: acc.deposit(200) |
| Constructor | __init__, which sets up a new object |
Common Mistakes
- Forgetting
selfas the first parameter of a method, which gives “takes 0 positional arguments but 1 was given”. - Writing
name = nameinstead ofself.name = name, so the value is never stored on the object. - Calling the class without arguments when
__init__requires them. - Misspelling
__init__with single underscores, so it never runs.
Practice Exercises
Exercise 1. Write a Rectangle class with width, height and an area() method.
Show answer
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
print(Rectangle(3, 4).area()) # 12
Exercise 2. Add a class attribute count to Student that goes up every time a student is created.
Show answer
Add count = 0 at class level and Student.count += 1 inside __init__.
Frequently Asked Questions
Is self a keyword in Python?
No, it is just the conventional name for the first parameter of a method. Any name would work, but always use self so others can read your code.
What is the difference between __str__ and __repr__?
__str__ is the friendly text for users and print(). __repr__ is the detailed text for developers, shown in the interactive shell and inside lists.
Is everything in Python an object?
Yes. Numbers, strings, lists and even functions and classes are objects with their own types and methods.
Summary
- A class is a blueprint; an object is one instance of it.
__init__sets up each new object, andselfrefers to that object.- Instance attributes are per object; class attributes are shared.
__str__controls how an object prints.
Next: reuse a class’s code with Python Inheritance.
