🖥 Manually specifying arithmetic operations between class objects can make your code less readable

mahabub.devs3
Mahabubur Rahman
Published on Nov, 21 2024 1 min read 0 comments
image

Manually specifying arithmetic operations between class objects can make your code less readable.

Python's _add__ method provides elegant arithmetic syntax between your class objects and makes your code more readable and intuitive.

 

Less readable example

class Animal:
    def __init__(self,species:str,weight:float):
        self.species = species
        self.weight = weight
        

tiger = Animal("Tiger",180)
lion = Animal("Lion",220)

total_weignt = tiger.weight+lion.weight
total_weignt # 400

 

More intuitive example 

class Animal:
    def __init__(self,species:str,weight:float):
        self.species = species
        self.weight = weight
        
    def __add__(self,other):
        return Animal(
            f"{self.species}+{other.species}",
            self.weight+other.weight
            )
        

tiger = Animal("Tiger",180)
lion = Animal("Lion",220)

combined = tiger+lion
combined.weight # 400

If you have any specific questions or need further assistance, feel free to ask!
 

0 Comments