How to create Class and Object in Python

What are classes and objects?

Classes and objects are like blueprints, and actual items are based on those blueprints. A class defines the structure and behaviours of things you want to model, while objects are instances of those things. For example, think of a “Car” class as the blueprint that defines what a car should have (attributes like colour, model, and methods like start_engine), and an actual car you see on the road as an object created based on that blueprint. Classes and objects help organize and manage code in a more logical and reusable way, making it easier to understand and work with complex systems or concepts.

How to create classes and objects in Python?

You can create classes and objects in Python to define and instantiate your data types. Here’s a step-by-step guide on how to create a class and instantiate objects from it:

  1. Creating a Class: To define a class, use the class keyword followed by the class name. You can also include attributes (variables) and methods (functions) within the class. Here’s a simple example of a Person class:
   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.")
  1. Instantiating Objects: To create an object (instance) of the class, call the class name followed by parentheses. You can pass any necessary arguments to the class’s init method. Here’s how you can create two Person objects:
   person1 = Person("Alice", 30)
   person2 = Person("Bob", 25)
  1. Accessing Attributes and Methods: Once you have objects, you can access their attributes and methods using the dot notation. Here’s how you can access the attributes and call the greet method:
   print(person1.name)  # Output: Alice
   print(person2.age)   # Output: 25

   person1.greet()  # Output: Hello, my name is Alice and I am 30 years old.
   person2.greet()  # Output: Hello, my name is Bob and I am 25 years old.

Classes provide a way to encapsulate data and behaviour into reusable units. They are a fundamental concept in object-oriented programming, allowing you to model real-world entities and their interactions within your Python programs.