What is the relationship between a class and an object in Python?

What is the relationship between a class and an object in Python?

a) A class is a blueprint for creating objects
b) An object is a blueprint for creating classes
c) A class and an object are the same thing
d) A class can only contain one object

Answer:

a) A class is a blueprint for creating objects

Explanation:

A class in Python is a blueprint or template for creating objects. It defines the attributes (data) and methods (behaviors) that the objects created from the class will have. An object, on the other hand, is an instance of a class with specific values for its attributes and the ability to perform actions using its methods.

class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species

    def make_sound(self):
        print(f"{self.name} makes a sound.")

# Creating objects (instances) of the Animal class
dog = Animal("Buddy", "Dog")
cat = Animal("Whiskers", "Cat")

dog.make_sound()  # Output: Buddy makes a sound.
cat.make_sound()  # Output: Whiskers makes a sound.

In this example, Animal is the class, serving as a blueprint for creating objects like dog and cat. Each object has its own unique attributes but shares the methods defined in the class.

The relationship between a class and an object is fundamental in OOP, as it allows you to create multiple instances of a class, each with its own state and behavior.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top