DEV Community

cristinalynn
cristinalynn

Posted on

Object Oriented Programming in Python

Let's start with what Python is. Python is an interpreted, object-oriented programming language. It is a high-level, versatile programming language known for its simplicity and readability.

Object-oriented programming or OOP in Python revolves around the concept of classes and objects. Object-oriented programming is a programming paradigm that provides a means of structuring programs so that properties and behaviors are bundled into individual objects.

For example, an object could represent a person with properties like a name, age, and address and behaviors such as walking, talking, breathing, and running. Or it could represent an email with properties like a recipient list, subject, and body and behaviors like adding attachments and sending.

Here is an overview of OOP concepts in Python:

Classes: A class is a blueprint for creating objects. It defines the attributes (data) and methods (functions) that characterize the objects. A Python class both contains the instructions for creating new objects and has the ability to create those objects. One of the biggest advantages of using classes to organize data is that instances are guaranteed to have the attributes you expect. In Python, you can define a class using the 'class' keyword.

class Car:
    # some code to describe a car

# new code goes here

Enter fullscreen mode Exit fullscreen mode

Objects (Instances): An object is an instance of a class. It is created using the class constructor (which is typically the class name followed by parentheses). Each object has its own set of attributes and can call the methods defined in the class.

car1 = Car("Toyota", "Camry")
car2 = Car("Tesla", "Model S")

car1.drive()  # Output: Toyota Camry is driving.
car2.drive()  # Output: Tesla Model S is driving.

Enter fullscreen mode Exit fullscreen mode

Attributes: Attributes are the data associated with a class or its objects. They are defined using variables within the class and are accessed using dot notation (object.attribute).

Methods: Methods are functions defined within a class. They operate on the attributes of the class and can perform various actions. Methods are crucial for encapsulating behavior within objects and enabling them to interact with their own data.

Constructor (init): The init method is a special method used for initializing objects. It is called automatically when an object is created and allows you to set initial values for object attributes.Here's how the init() method works:

Initialization: The init() method initializes the
object's attributes with the values provided as arguments when creating an instance of the class.

Automatic Invocation: When you create an instance of a class using the class name followed by parentheses (i.e., the constructor), Python automatically calls the init() method.

Self Parameter: The self parameter is used to refer
to the instance itself. Inside the init() method, self is used to access and set the instance's attributes.

Here is a simple example demonstrating the usage of init():

      class Person:
           def __init__(self, name, age):
           self.name = name
           self.age = age

      # Creating instances of the Person class
       person1 = Person("Alice", 30)
       person2 = Person("Bob", 25)

       print(person1.name, person1.age)  # Output: Alice 30
       print(person2.name, person2.age)  # Output: Bob 25

Enter fullscreen mode Exit fullscreen mode

Inheritance: Inheritance is a feature of OOP that allows a class (subclass) to inherit the attributes and methods of another class (superclass). In other words, one class takes on the attributes and methods of another. Newly formed classes are called child classes, and the classes that you derive child classes from are called parent classes. Child classes can override or extend the attributes and methods of parent classes. In other words, child classes inherit all of the parent’s attributes and methods but can also specify attributes and methods that are unique to themselves. One thing to keep in mind about class inheritance is that changes to the parent class automatically propagate to child classes. This occurs as long as the attribute or method being changed isn’t overridden in the child class. In Python, you can achieve inheritance using the syntax class Subclass(Superclass).

class ElectricCar(Car):
    def __init__(self, brand, model, battery_capacity):
        super().__init__(brand, model)
        self.battery_capacity = battery_capacity

    def charge(self):
        print(f"{self.brand} {self.model} is charging.")

Enter fullscreen mode Exit fullscreen mode

Encapsulation: Encapsulation is the bundling of data and methods that operate on the data within a single unit (class). It helps in hiding the internal state of an object and preventing it from being accessed directly from outside the class.

Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common superclass. This enables code to work with objects of multiple types through a uniform interface.

These are some of the key concepts of object-oriented programming in Python. OOP provides a powerful way to structure and organize code, making it more modular, reusable, and easier to maintain.

Top comments (0)