top of page

OOP - Crib Sheet



Object-oriented programming (OOP) is a popular programming paradigm that allows developers to create reusable code by using objects that encapsulate data and behavior. Python is a versatile programming language that supports object-oriented programming, making it easy to create classes, objects, and methods.


In this article, we will explore various aspects of object-oriented programming in Python, including class, operator overloading, protocols, special methods, subclassing, inheritance, and OOP-related decorators.


Class


In Python, a class is a blueprint for creating objects. It defines the properties and methods that an object will have. The following is an example of a class definition in Python:

class Car: 
    def __init__(self, make, model, year): 
        self.make = make self.model = model 
        self.year = year 

    def get_make(self): 
        return self.make
 
    def get_model(self): 
        return self.model 

    def get_year(self): 
        return self.year

In this example, we define a class called Car. The __init__ method is a special method that gets called when an object of the class is created. It initializes the make, model, and year attributes of the object.


We also define three methods that get the make, model, and year attributes of the object. These methods are called instance methods because they operate on an instance of the class.


Operator Overloading


Operator overloading is a technique in OOP that allows operators to be used with user-defined classes. Python supports operator overloading through special methods. For example, the + operator can be overloaded to concatenate two objects of a class. Here is an example:

class Point: 
    def __init__(self, x, y): 
        self.x = x 
        self.y = y 
        
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y) 
        
    def __str__(self): 
        return "({}, {})".format(self.x, self.y) 
        
p1 = Point(1, 2) 
p2 = Point(3, 4) 

p3 = p1 + p2
 
print(p3) # Output: (4, 6)

In this example, we define a class called Point that represents a point in 2D space. We overload the + operator using the __add__ special method to add two Point objects together.


Protocols


In Python, a protocol is a set of methods and attributes that a class must implement to be considered a member of that protocol. Protocols are used to define a common interface that multiple classes can implement. For example, the Iterable protocol defines a common interface for objects that can be iterated over.

Here is an example of a class that implements the Iterable protocol:

class FibonacciSequence: 
    def __init__(self, limit): 
        self.limit = limit 

    def__iter__(self): 
        self.current = 0 
        self.next = 1 
        return self 

        def __next__(self): 
        if self.current > self.limit: 
            raise StopIteration 

        result = self.current 
        self.current, self.next = self.next, self.current + self.next 
        return result

In this example, we define a class called FibonacciSequence that implements the Iterable protocol. It generates a sequence of Fibonacci numbers up to a specified limit.


Special Methods


Special methods are methods that begin and end with double underscores (__). They are also called magic methods or dunder methods. These methods are used to customize the behavior of built-in functions and operators when applied to objects of the class.

For example, the __str__ method is a special method that returns a string representation of an object. Here is an example:


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

    def__str__(self): 
        return "{} ({})".format(self.name, self.age) 
p = Person("John", 30)

print(p) # Output: John (30)

In this example, we define a class called Person that represents a person. We overload the __str__ special method to return a string representation of the person.


Subclassing and Inheritance

In Python, subclassing is a technique that allows a new class to be derived from an existing class. The new class inherits all the properties and methods of the existing class and can add or modify its own properties and methods.


Here is an example of subclassing:

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

def speak(self): 
    raise NotImplementedError("Must implement abstract method")
     
class Dog(Animal): 
    def speak(self): 
        return "Woof" 

class Cat(Animal): 
    def speak(self): 
        return "Meow" 
        
d = Dog("Rufus") 
c = Cat("Fluffy")
 
print(d.speak()) # Output: Woof 
print(c.speak()) # Output: Meow

In this example, we define a base class called Animal that has a property name and an abstract method speak. We then define two subclasses, Dog and Cat, that inherit from Animal and implement their own speak method.


OOP-Related Decorators


Python provides a number of built-in decorators that are used in OOP. Decorators are used to modify the behavior of functions and methods. Here are some examples:

  • @classmethod: A decorator that defines a method that operates on the class rather than an instance of the class.

class Person: 
    count = 0 

    def __init__(self, name, age): 
        self.name = name 
        self.age = age 
        Person.count += 1 

    @classmethod
        def get_count(cls): 
            return cls.count 
            
p1 = Person("John", 30) 
p2 = Person("Jane", 25) 

print(Person.get_count()) # Output: 2

In this example, we define a class method called get_count using the @classmethod decorator. The method returns the number of Person objects that have been created.

  • @staticmethod: A decorator that defines a method that does not operate on the instance or the class, but is related to the class in some way.

class Math: 
    @staticmethod 
    def add(x, y): 
        return x + y 
        
print(Math.add(2, 3)) # Output: 5

In this example, we define a static method called add using the @staticmethod decorator. The method adds two numbers together.

  • @property: A decorator that defines a method that can be accessed like a property.

class Circle: 
    def __init__(self, radius): 
        self.radius = radius 
        
    @property 
    def diameter(self): 
        return self.radius * 2 
        
c = Circle(5) print(c.diameter) # Output: 10

In this example, we define a class called Circle that has a property radius. We define a method called diameter using the @property decorator. This method calculates and returns the diameter of the circle based on the radius property.


Object-oriented programming is a powerful programming paradigm that allows us to model complex systems in a clear and concise manner. Python provides a number of tools and constructs that make it easy to implement OOP concepts such as class, operator overloading, protocols, special methods, subclassing and inheritance, and OOP-related decorators.




442 views0 comments

Recent Posts

See All
bottom of page