In this challenge, you need to implement a method that squares passing variables and returns their sum.
Problem statement
Implement a class Point that has three properties and a method. All these attributes (properties and methods) should be public. This problem can be broken down into two tasks:
Task 1
Implement a constructor to initialize the values of three properties: x, y, and z.
Task 2
Implement a method, sqSum(), in the Point class which squares x, y, and z and returns their sum.
Sample properties: 1, 3, 5
Sample method output: 35
Coding exercise
First, take a close look at the slides above and then design a similar step-by-step algorithm before jumping to its implementation.
1 2 3 4 5 6 7 8 | class Point: def __init__(self): self.x = x self.y = y self.z = z def sqSum(self): pass |
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def sqSum(self): a = self.x * self.x b = self.y * self.y c = self.z * self.z return(a + b + c) obj1 = Point(4, 5, 6) print(obj1.sqSum()) |
Explanation
Task 1:
We passed parameters and assigned them to their corresponding properties.
Task 2:
We calculated the squares of the properties by multiplying them with itself and stored them in a variable.
Then, we added all the squared numbers.
Finally, we returned their sum