Back to Freecodecamp

Step 5

curriculum/challenges/english/blocks/learn-encapsulation-by-building-a-projectile-trajectory-calculator/660fcf3e1b9bb056b2edb567.md

latest2.7 KB
Original Source

--description--

At this point you are ready to create the string representation. Start by creating an instance of the Projectile class. Below the class definition, create a ball variable and assign it a call to Projectile using 10, 3, 45 as arguments.

Define a __str__ method within the class, to give your instance a proper string representation, and make it return a string with the following format:

py

Projectile details:
speed: 10 m/s
height: 3 m
angle: 45°
displacement: 12.6 m

It should start and end with a new line character, the angle has to be written as an integer in degrees and the displacement should be printed with one decimal digit.

You will find useful math.degrees to convert the angle from radians to degrees.

When you are ready you can print(ball) to test your function.

--hints--

You should have a ball variable.

js
({test: () => assert(runPython(`_Node(_code).has_variable('ball')`))})

The ball variable should have a value of Projectile(10, 3, 45).

js
({test: () => assert(runPython(`_Node(_code).find_variable('ball').is_equivalent('ball = Projectile(10, 3, 45)')`))})

The string representation for Projectile(45, 45, 45) should be correct.

js
({test: () => assert(runPython(
`
ball = Projectile(45, 45, 45)
str(ball) == """
Projectile details:
speed: 45 m/s
height: 45 m
angle: 45°
displacement: 244.4 m
"""`
))})

The string representation should also be correct for other instances.

js
({test: () => assert(runPython(`p = Projectile(10, 10, 10)
str(
    p
) == """
Projectile details:
speed: 10 m/s
height: 10 m
angle: 10°
displacement: 15.9 m
"""`))})

You should have a print(ball) call.

js
({
    test: () => runPython(`
    calls = _Node(_code).find_calls('print')
    assert any(c.is_equivalent('print(ball)') for c in calls)
    `)
})

--seed--

--seed-contents--

py
import math

GRAVITATIONAL_ACCELERATION = 9.81
PROJECTILE = "∙"
x_axis_tick = "T"
y_axis_tick = "⊣"

class Projectile:
    __slots__ = ('__speed', '__height', '__angle')

    def __init__(self, speed, height, angle):
        self.__speed = speed
        self.__height = height
        self.__angle = math.radians(angle)


    def __calculate_displacement(self):
        horizontal_component = self.__speed * math.cos(self.__angle)
        vertical_component = self.__speed * math.sin(self.__angle)
        squared_component = vertical_component**2
        gh_component = 2 * GRAVITATIONAL_ACCELERATION * self.__height
        sqrt_component = math.sqrt(squared_component + gh_component)
        
        return horizontal_component * (vertical_component + sqrt_component) / GRAVITATIONAL_ACCELERATION
        
--fcc-editable-region--

--fcc-editable-region--