Classes and Objects
Classes and Objects
In the last lesson, you learned that:
- a class is a blueprint
- an object is something created from that blueprint
Now let us understand classes and objects more clearly.
Real Example
Think about a cookie cutter.
- The cutter shape = class
- Each cookie made from it = object
One class can create many objects.
Create a Class
Use the class keyword.
class Car:
pass
This creates a class named Car.
Create Objects
Use the class name with parentheses.
class Car:
pass
car1 = Car()
car2 = Car()
print(car1)
print(car2)
Output Example
<__main__.Car object at ...>
<__main__.Car object at ...>
The addresses are different because they are different objects.
Why Create Many Objects?
You may need many cars, many users, many products, or many students.
One class can create them all.
Another Example
class Student:
pass
tom = Student()
sara = Student()
print(tom)
print(sara)
Objects Are Independent
Each object is separate.
Changing one object later does not automatically change another object.
Naming Rule
By convention:
-
Class names use CapitalWords:
CarStudentBankAccount
-
Object names use lowercase:
car1student1
Real World Examples
Userclass → many usersProductclass → many productsOrderclass → many ordersEnemyclass → many game enemies
Code Along
Create a class called Book.
Create two objects:
book1book2
Print both objects.
Mini Challenge
Create a class called Laptop.
Steps:
-
Create three objects:
laptop1laptop2laptop3
-
Print all three objects
Expected output:
<__main__.Laptop object at ...>
<__main__.Laptop object at ...>
<__main__.Laptop object at ...>
Real World Use Case
Online stores use product objects. Schools use student objects. Games use player and enemy objects.
Quiz
- What is a class?
- What is an object?
- Can one class create many objects?
- Why do printed objects show different addresses?
Assignment
Create a class called Phone and create four phone objects.
Summary
You learned how classes act as blueprints and how many separate objects can be created from one class.