Python Classes and Objects

Classes and objects are fundamental concepts in object-oriented programming (OOP). Python, being an object-oriented language, allows you to create and use classes and objects to model real-world entities and their interactions.


What are Classes and Objects?

  • Class: A class is a blueprint for creating objects. It defines a set of attributes and methods that the objects created from the class will have.
  • Object: An object is an instance of a class. It is created using the class definition and can have its own unique values for the attributes defined by the class.




Creating a Class

To create a class in Python, you use the class keyword followed by the class name and a colon:

class Animal:
    # Class attributes and methods go here




The __init__ Method

The __init__ method is a special method that is called when an object is instantiated. It initializes the object’s attributes.

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




Creating an Object

To create an object, you call the class using its name and pass any arguments required by the __init__ method:

cat = Animal("Whiskers", "Cat")
print(cat.name)  # Output: Whiskers
print(cat.species)  # Output: Cat




Instance Methods

Instance methods are functions defined within a class that operate on instances of the class. They can access and modify the attributes of the class.

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

    def make_sound(self, sound):
        return f"{self.name} says {sound}"




Python Classes and Objects Example

Example: Dog Class

class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

    def bark(self):
        return f"{self.name} says Woof!"

dog = Dog("Buddy", "Golden Retriever")
print(dog.name)  # Output: Buddy
print(dog.bark())  # Output: Buddy says Woof!




Python Labs

Scroll to Top