Introduction to Python Object-Oriented Programming (OOP)

OOP is a programming paradigm based on the concept of "objects," which can contain data (attributes) and code (methods) that operate on that data.

Defining a Class


    class Dog:
      def __init__(self, name, breed):
        self.name = name
        self.breed = breed
    
      def bark(self):
        print("Woof!")
        

This defines a class called Dog. The __init__ method is a special method (constructor) that is called when a new object (instance) of the class is created.

Creating an Object (Instance)


    my_dog = Dog("Buddy", "Golden Retriever")
    print(my_dog.name)  # Output: Buddy
        

Accessing Attributes


    print(my_dog.breed)  # Output: Golden Retriever
        

Calling Methods


    my_dog.bark()  # Output: Woof!
        

Adding More Attributes and Methods


    class Dog:
      def __init__(self, name, breed, age):
        self.name = name
        self.breed = breed
        self.age = age
    
      def bark(self):
        print("Woof!")
    
      def get_age(self):
        return self.age
        
    my_dog2 = Dog("Lucy", "Labrador", 3)
    print(my_dog2.get_age())
        

Example: Calculating Area of Shapes


    class Rectangle:
      def __init__(self, width, height):
        self.width = width
        self.height = height
    
      def area(self):
        return self.width * self.height
    
    rect = Rectangle(5, 10)
    print(rect.area())  # Output: 50
    
    class Circle:
        def __init__(self, radius):
            self.radius = radius
    
        def area(self):
            return 3.14159 * (self.radius * self.radius)
    
    
    circle = Circle(7)
    print(circle.area())
        

Important Concepts

  • Class: A blueprint for creating objects.
  • Object (Instance): An actual instance of a class.
  • Attribute: A characteristic of an object (e.g., name, breed).
  • Method: A function that belongs to a class and operates on the object's attributes.
  • Constructor (`__init__`): A special method that initializes the attributes of a new object.