exception

Python Classes and Objects

Python Classes and Objects

Classes and objects are the foundation of Object-Oriented Programming (OOP). A class is a blueprint for creating objects, and an object is an instance of a class.

Creating a Class

To create a class, you use the class keyword:

      
        class Person:
            def __init__(self, name, age):
                self.name = name
                self.age = age
            
            def greet(self):
                print(f"Hello, my name is {self.name} and I am {self.age} years old.")
        
        # Create an object of the class
        person1 = Person("Alice", 25)
        person1.greet()
      
    

The __init__ method is the constructor that initializes an object, and the greet method is a function that belongs to the class.

Activity

Try It Yourself!

Create a Car class with attributes make and model, and a method that prints the car's information.

Quick Quiz

Quick Quiz

  1. What is the difference between a class and an object?
  2. What is the purpose of the __init__ method in Python classes?

Answers: A class is a blueprint for creating objects, while an object is an instance of the class. The __init__ method initializes the attributes of the object when it is created.