100k views
5 votes
Implement a class, Gram, that represents the mass unit grams.

The class should contain the following
Constructor
a) init_(self, value=0)
Instance Variables
1) value size of the mass
Methods
i) toKilos () returns value but in kilos, i.e., divides value by 1000
ii) toPounds () -returns value but in US pounds, i.e., multiple value by 0.00220462
iii) _add__(other) - returns a new Gram object whose value is the sum of itself and other
iv) sub__(other) returns a new Gram object whose value is the difference of itself and other. If value is less than zero, set it to zero.

1 Answer

3 votes

Final answer:

The Gram class represents mass in grams with methods to convert to kilograms and pounds and to perform addition and subtraction with other Gram objects, ensuring no negative mass values.

Step-by-step explanation:

The question requires the implementation of a class in a programming context, specifically a class named Gram to represent mass in grams. This class should have a constructor to initialize the mass value, and include methods to convert the mass to other units such as kilograms and pounds. Additionally, it should be able to add and subtract mass values while ensuring the result never falls below zero.

Methods of the class include toKilos() which converts the gram value to kilograms by dividing the original value by 1000, and toPounds() which converts grams to US pounds by multiplying the value by 0.00220462. The add method allows for the addition of two Gram objects, whereas the sub method handles subtraction. If the resulting value of sub is less than zero, it is set to zero to prevent negative mass.

User Jeremy Conley
by
8.5k points