Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

Python Class and Object


  • Blueprint or template for creating objects.
  • Defines structure and behavior for objects of that class.
  • Encapsulates data (attributes) and functions (methods) operating on that data.


  • Specific instance of a class.
  • Real-world manifestation of the class blueprint.
  • Possesses unique data (attributes) and can execute defined actions (methods).


Let’s say we have a class ‘Animal’:

# Define a class named Animal
class Animal:
    # Class attributes
    type = "bird"  
    name = "parrot"  

    # Define a method named display_info
    def display_info(self):
        print("I'm a", self.type)
        print("My name is",

# Create an instance of the Animal class
my_pet = Animal()

# Access class attributes and call the method through the object

In this code

1. Class Definition:

  • class Animal:: This line defines a class named Animal, which acts as a blueprint for creating objects.
  • type = “bird” and name = “parrot”: These are class attributes. They provide initial values that all instances of the class will have.
  • def display_info(self):: This defines a method named display_info. Methods are functions defined inside a class. The self parameter refers to the instance of the class and is used to access its attributes and methods.

2. Object Instantiation:

  • my_pet = Animal(): This line creates an instance of the Animal class called my_pet. This instance will have its own set of attributes, separate from any other instances of the class.

3. Accessing Attributes and Calling Methods:

  • print(my_pet.type): This line prints the value of the type attribute for the my_pet instance. It will output “bird”.
  • my_pet.display_info(): This line calls the display_info method on the my_pet instance. The method executes and prints “I’m a bird” and “My name is parrot”.