Solution 1

class Loan(object):
    def __init__(self, value):
        self.value = value

class Movie(object):
    def __init__(self, price):
        self.price = price

class Milk(object):
    def __init__(self, cost):
        self.cost = cost


def calculate(p1, p2):
    total = 0
    for product in [p1, p2]:
        for attr in ['cost', 'price', 'value']:
            if hasattr(product, attr):
                total += getattr(product, attr)
    return total

Price, cost and value

This is a simple assignment to demonstrate the power of Duck Typing. There are three classes already implemented (Loan, Movie, Milk) but each one of them has a different attribute to represent "value". Loan has value, Movie has price and Milk has cost.

Your job is to implement the highly dynamic calculate function that takes two objects, that can be of any type (Loan, Movie, Milk) and returns the total of the sum of their attributes. The key is to never check for types and to have a dynamic function with as few hardcoded names as possible.

Once you're done, check the solution and compare!

Test Cases

test calculate - Run Test

def test_calculate():
    obj1 = Loan(10)
    obj2 = Movie(5)
    obj3 = Milk(1)

    assert calculate(obj1, obj2) == 15
    assert calculate(obj1, obj3) == 11

    assert calculate(obj2, obj3) == 6

    assert calculate(obj3, obj3) == 2
######################## # These are already implemented. No need to change them: class Loan(object): def __init__(self, value): self.value = value class Movie(object): def __init__(self, price): self.price = price class Milk(object): def __init__(self, cost): self.cost = cost ######################## # Your task: def calculate(p1, p2): pass