Home > database >  Why do we pass arguments into a method instead of assigning them as attributes?
Why do we pass arguments into a method instead of assigning them as attributes?

Time:08-18

I am attempting to learn OOP in Python so I wanted to ask why do we pass parameters into the method when calling it, while the object is passed automatically by Python into the method as the first parameter and can be used to automatically identify and call its attributes instead of passing them when calling the method?

Why don't we do this:

class Item:
    def calculate_total(self):
        total = self.quantity * self.price
        return total

item = Item()
item.price = 100
item.quantity = 5
item.calculate_total()

instead of this:

class Item:
    def calculate_total(self, x, y):
        total = x * y
        return total

item = Item()
item.price = 100
item.quantity = 5
item.calculate_total(item.price, item.quantity)

CodePudding user response:

The question is kinda flawed, as none of those should be seen in real-life code. Attributes should be declared inside the class, preferrably at the moment of object initialisation.

class Item:
    def __init__(self, price, quantity):
        self.price = price
        self.quantity = quantity
    def calculate_total(self):
        total = self.quantity * self.price
        return total

item = Item(100, 5)
item.calculate_total()

This way we don't have a risk of self.price and self.quantity not being defined when we call calculate_total.

But, even with what you provided, why 2nd method would be worse quickly becomes apparent if you try to calculate things multiple times. Let's say you've got 3 slightly different totals (different currency maybe). Would you rather write

item.calculate_total1(item.price, item.quantity)
item.calculate_total2(item.price, item.quantity)
item.calculate_total3(item.price, item.quantity)

or

item.calculate_total1()
item.calculate_total2()
item.calculate_total2()

?

As @Pranav Hosangadi mentions, if there are any parameters that do not have a place in the attributes of a class (e.g. discount, which can vary for different sales of the same item), that is where we would pass them to the method:

class Item:
    def __init__(self, price, quantity):
        self.price = price
        self.quantity = quantity
    def calculate_total(self, discount):
        total = self.quantity * self.price * (1 - discount)
        return total

item = Item(100, 5)
discount = 0.15
print(item.calculate_total(discount))
  • Related