create function that lets you divide variables with multiple paramaters

Viewed 30

Making a food log that has multiple entries. Each entry has name, calories, fat, carbs, protein, serving size, in that order.

IE:

chicken_salad_sandwich = FoodValues('Chicken Salad Sandwich', calories=600, fat=18, carbs=48, protein=25, serv_size=250)

How do I write code that lets me divide the item in whatever manner I desire?

This is what I want to return if I divide variable 'chicken_salad_sandwich ' by two:

FoodValues('Chicken Salad Sandwich', calories=300, fat=9, carbs=24, protein=12.5, serv_size=125)

Here's the code that multiplies:

def __mul__(self, other):
    if other == 0:
        return 0

    # Other than 0, food values can only be multiplied by an int
    if not isinstance(other, int):
        return NotImplemented

    selfname = self.name
    if '+' in selfname:
        # Quick and dirty grouping symbol
        selfname = f'({selfname})'

    return FoodValues(
        f'{other} {selfname}',
        self.fat * other,
        self.carbs * other,
        self.protein * other,
        self.serv_size * other,
        self.calories * other,
    )
1 Answers

Re-wrote your code for __div__. I believe this is what you are asking for (I also made it divide only by int)

def __div__(self, other):
    if other == 0:
        return 0

    # Other than 0, food values can only be divided by an int
    if not isinstance(other, int):
        return NotImplemented

    selfname = self.name
    if '+' in selfname:
        # Quick and dirty grouping symbol
        selfname = f'({selfname})'

    return FoodValues(
        f'{other} {selfname}',
        self.fat / other,
        self.carbs / other,
        self.protein / other,
        self.serv_size / other,
        self.calories / other,
    )

(I believe it is div, let me know if not)

Related