Solution 1

class Distance(object):
    def __init__(self, meters=None, feet=None):
        if not any((meters, feet)):
            raise ValueError("Provide at least one measure of distance")

        self.meters = meters
        self.feet = feet

    @property
    def distance_in_meters(self):
        return self.meters or self.feet / 3.28

    @property
    def distance_in_feet(self):
        return self.feet or self.meters * 3.28

    @property
    def distance_in_kilometers(self):
        return self.distance_in_meters / 1000.0

    @property
    def distance_in_miles(self):
        return self.distance_in_kilometers / 1.6


d = Distance(meters=8000)
assert d.distance_in_kilometers == 8, d.distance_in_miles
assert d.distance_in_miles == 5, d.distance_in_miles

Distance properties

Implement the Distance class from our reading providing different properties for each distance unit. A distance can be created using either meters or feet. The Distance can then convert to kilometers, miles, feet or meters.

Test Cases

test meters to feet - Run Test

def test_meters_to_feet():
    d = Distance(meters=8000)

    assert d.distance_in_meters == 8000
    assert d.distance_in_feet == 26240

test meters to miles - Run Test

def test_meters_to_miles():
    d = Distance(meters=8000)

    assert d.distance_in_meters == 8000
    assert d.distance_in_miles == 5

test feet to kilometers - Run Test

import pytest


def test_feet_to_kilometers():
    d = Distance(feet=25000)

    assert d.distance_in_feet == 25000
    assert d.distance_in_kilometers == pytest.approx(7.62, rel=1e-2)

test feet to meter - Run Test

import pytest

def test_feet_to_meter():
    d = Distance(feet=25000)

    assert d.distance_in_feet == 25000
    assert d.distance_in_meters == pytest.approx(7621.95, rel=1e-2)

test meters to kilometers - Run Test

def test_meters_to_kilometers():
    d = Distance(meters=8000)

    assert d.distance_in_meters == 8000
    assert d.distance_in_kilometers == 8

test feet to miles - Run Test

import pytest

def test_feet_to_miles():
    d = Distance(feet=25000)

    assert d.distance_in_feet == 25000
    assert d.distance_in_miles == pytest.approx(4.76, rel=1e-2)
class Distance(object): def __init__(self, meters=None, feet=None): # Please don't change this method if not any((meters, feet)): raise ValueError("Provide at least one measure of distance") self.meters = meters self.feet = feet