The Idea of Objects
Look at your phone. It has data about itself: brand, battery level, contacts. It can also do things: make a call, take a photo, charge. Programmers found that organising code in the same way, with each "thing" holding its own data and its own actions, makes big programs much easier to understand. This idea is called object-oriented programming.
In this lesson you will group data with Python dictionaries and JavaScript objects, see that you have been using objects all along, and write your first class: a blueprint for making objects.
The problem: scattered data
Suppose you store a student's details in separate variables:
student_name = "Aarav"
student_city = "Rohtak"
student_marks = 81With one student that is fine. With forty students you would need 120 variables, and nothing in the code says which name belongs with which marks. It would be much better to keep each student's details together, in one value.
Grouping data: dictionaries and objects
Python has the dictionary (dict) and JavaScript has the object. Both store data as key-value pairs: a name (the key) and its value. The idea is the same as a real dictionary, where you look up a word to find its meaning.
student = {"name": "Aarav", "city": "Rohtak", "marks": 81}
print(student["name"])
print(student["marks"])
student["marks"] = 86
student["house"] = "Blue"
print(student)Aarav
81
{'name': 'Aarav', 'city': 'Rohtak', 'marks': 86, 'house': 'Blue'}const student = { name: "Aarav", city: "Rohtak", marks: 81 };
console.log(student.name);
console.log(student.marks);
student.marks = 86;
student.house = "Blue";
console.log(student);Aarav
81
{ name: 'Aarav', city: 'Rohtak', marks: 86, house: 'Blue' }Python reads a value with square brackets and the key in quotes: student["name"]. JavaScript usually uses a dot: student.name. In both, you can change a value or add a new key at any time.
A list of these makes a neat table, one dictionary or object per student:
students = [
{"name": "Aarav", "marks": 81},
{"name": "Priya", "marks": 94},
{"name": "Rohan", "marks": 67},
]
for s in students:
print(f"{s['name']} scored {s['marks']}")Aarav scored 81 Priya scored 94 Rohan scored 67
You have been using objects all along
In Python and JavaScript, almost every value is an object with its own built-in actions. An action that belongs to an object is called a method, and you call it with a dot:
"pune".upper()asks the string object to give a capitalised copy of itself.marks.append(90)asks the list object to add an item to itself.prices.toSorted()asks the JavaScript array to give a sorted copy.
So an object is a bundle of data (also called properties or attributes) and methods that work on that data.
Classes: blueprints for objects
A class is a blueprint that describes what data and methods a kind of object has. You can then make as many objects from it as you like. Think of an admission form: the printed blank form is the class, and each filled-in form, one per student, is an object.
Here is a class for a simple payment wallet. Each wallet has an owner and a balance, and it can add money and make payments. It also follows a rule: you cannot pay more than you have.
class Wallet:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def add_money(self, amount):
self.balance += amount
print(f"{self.owner} added ₹{amount}. Balance: ₹{self.balance}")
def pay(self, shop, amount):
if amount > self.balance:
print(f"{self.owner}'s payment to {shop} failed: balance is ₹{self.balance}")
else:
self.balance -= amount
print(f"{self.owner} paid ₹{amount} to {shop}. Balance: ₹{self.balance}")
isha = Wallet("Isha", 500)
farhan = Wallet("Farhan")
isha.pay("Chai Point", 40)
farhan.pay("Chai Point", 40)
farhan.add_money(200)
farhan.pay("Chai Point", 40)Isha paid ₹40 to Chai Point. Balance: ₹460 Farhan's payment to Chai Point failed: balance is ₹0 Farhan added ₹200. Balance: ₹200 Farhan paid ₹40 to Chai Point. Balance: ₹160
The important pieces:
class Wallet:starts the blueprint. Class names start with a capital letter by custom.__init__is a special method that runs when you create a new object. It sets up the object's starting data.selfmeans "this particular wallet".self.balanceis this wallet's balance, so Isha's money and Farhan's money never mix.Wallet("Isha", 500)creates a new object, also called an instance, from the class.
Here is the same class in JavaScript. The setup method is called constructor, this plays the role of self, and you create objects with the keyword new:
class Wallet {
constructor(owner, balance = 0) {
this.owner = owner;
this.balance = balance;
}
addMoney(amount) {
this.balance += amount;
console.log(`${this.owner} added ₹${amount}. Balance: ₹${this.balance}`);
}
pay(shop, amount) {
if (amount > this.balance) {
console.log(`${this.owner}'s payment to ${shop} failed: balance is ₹${this.balance}`);
} else {
this.balance -= amount;
console.log(`${this.owner} paid ₹${amount} to ${shop}. Balance: ₹${this.balance}`);
}
}
}
const isha = new Wallet("Isha", 500);
const farhan = new Wallet("Farhan");
isha.pay("Chai Point", 40);
farhan.pay("Chai Point", 40);
farhan.addMoney(200);
farhan.pay("Chai Point", 40);Isha paid ₹40 to Chai Point. Balance: ₹460 Farhan's payment to Chai Point failed: balance is ₹0 Farhan added ₹200. Balance: ₹200 Farhan paid ₹40 to Chai Point. Balance: ₹160
Why objects help
- Data and rules stay together. The "cannot pay more than the balance" rule lives inside
pay(), so every wallet obeys it automatically. - Many objects, one blueprint. A shop app might have thousands of wallets, all created from the same class.
- Code matches the real world. A railway program can have
Train,CoachandPassengerclasses, which makes it easier for people to understand.
You do not need classes for small scripts. Dictionaries and functions are often enough. Classes earn their place as programs grow. You can go much deeper in Classes & Objects and JavaScript Classes.
Common mistakes
- Forgetting
selfin Python. Every method needsselfas its first parameter, and data must be written asself.balance, not justbalance. - Forgetting
newin JavaScript.Wallet("Isha")withoutnewfails withTypeError: Class constructor Wallet cannot be invoked without 'new'. - A misspelt key.
student["mark"]raisesKeyError: 'mark'in Python;student.markquietly givesundefinedin JavaScript. - Mixing up class and object. The class is the blueprint; each object made from it holds its own data.
Key points
- Objects bundle related data (properties) with the actions (methods) that work on it.
- Python dictionaries and JavaScript objects store key-value pairs:
d["key"]andobj.key. - Strings and lists are objects too;
upper()andappend()are their methods. - A class is a blueprint; an object (instance) is one thing made from it.
- Python uses
__init__andself; JavaScript usesconstructor,thisandnew.
Exercise
Write a Student class in Python. Each student has a name and a list of marks. Add a method average() that returns the average of the marks, and a method has_passed() that returns True if the average is 33 or more. Create two students, Meera with marks 72, 85, 90 and Kabir with marks 25, 30, 38, and print each one's name, average (one decimal place) and result.
Show solution
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def average(self):
return sum(self.marks) / len(self.marks)
def has_passed(self):
return self.average() >= 33
for s in [Student("Meera", [72, 85, 90]), Student("Kabir", [25, 30, 38])]:
result = "Pass" if s.has_passed() else "Fail"
print(f"{s.name}: average {s.average():.1f}, {result}")Meera: average 82.3, Pass Kabir: average 31.0, Fail
has_passed() calls the object's own average() method through self. The line "Pass" if ... else "Fail" is a short way to choose between two values.
Quick Quiz
1. In student = {"name": "Isha", "marks": 91}, how do you read the marks in Python?
Python dictionaries use square brackets with the key; JavaScript objects usually use a dot.
2. What is a class?
Objects (instances) are made from a class, like filled-in copies of a blank form.
3. In a Python method, what does self refer to?
self lets each object keep its own data, such as its own balance.
4. Which keyword creates an object from a class in JavaScript?
new Wallet("Isha", 500) calls the constructor and returns the new object.
Learn Intro to Programming with a mentor
Free lessons get you started. Our Python Programming training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
