CodingNic

Object-Oriented Programming

Classes and Objects

Object-Oriented Programming 26 min read

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.

python
class Car:
    pass

This creates a class named Car.

Create Objects

Use the class name with parentheses.

python
class Car:
    pass

car1 = Car()
car2 = Car()

print(car1)
print(car2)

Output Example

text
<__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

python
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:

    • Car
    • Student
    • BankAccount
  • Object names use lowercase:

    • car1
    • student1

Real World Examples

  • User class → many users
  • Product class → many products
  • Order class → many orders
  • Enemy class → many game enemies

Code Along

Create a class called Book.

Create two objects:

  • book1
  • book2

Print both objects.

Mini Challenge

Create a class called Laptop.

Steps:

  • Create three objects:

    • laptop1
    • laptop2
    • laptop3
  • Print all three objects

Expected output:

text
<__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

  1. What is a class?
  2. What is an object?
  3. Can one class create many objects?
  4. 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.