Как я могу изменить / расширить следующий код python, чтобы вычислить мг (милиграмм?) - PullRequest
0 голосов
/ 09 января 2020

Я хочу расширить следующий код, чтобы рассчитать и миллиграммы. Может кто-нибудь сказать мне, как?

class weight:

    __metric = {"g" : 1,
                "kg" : 1000,
                 }
    def __init__(self, value, unit = "g"):
        self.value = value
        self.unit = unit
    def convert_to_gram(self):
        return self.value * weight._metric[self.unit]
    def __add__(self,other):
        x = self.convert_to_gram() + other.convert_to_gram()
        return weight + (x/weight._metric[self.unit], self.unit)
    def __str__(self):
        return "{} {}".format (self.value, self.unit)

1 Ответ

0 голосов
/ 09 января 2020
class weight:
    def __init__(self, value, unit = "g"):
        """
        This method is initialized when the object is created
        """
        self.value = value
        self.unit = unit
        # The value of kg is 0.001 (1E-3) because your logic multiplies the input value. So mg must be 1/1E-3 = 1000
        self._metric = {"g" : 1,
                    "kg" : 0.001,
                    "mg" : 1000
                   }

    def convert_to_gram(self):
        """
        This method converts a self.value to g, kg or mg based on self.unit
        """
        return self.value * self._metric[self.unit]

    def __add__(self, other):
        """
        The __add__ method is a 'magic' (dunder) method which gets called when we add two numbers using the + operator.
        this method calls convert_to_gram() methods from this class object and from 'other' class object as well
        it then returns the sum of both convertion results from the two objects
        """
        x = self.convert_to_gram() + other.convert_to_gram()
        return (x/self._metric[self.unit], self.unit)

    def __str__(self):
        return "{} {}".format (self.value, self.unit)


w1 = weight(100, 'mg')  # create object w1
w2 = weight(50, 'mg')  # create object w2

# call convert_to_gram() to convert 100 to mg and save the result in result_w1
result_w1 = w1.convert_to_gram()
print(result_w1)

# call convert_to_gram() to convert 50 to mg and save the result in result_w2
result_w2 = w2.convert_to_gram()
print(result_w2)

print(w1 + w2)

Дает:

100000
50000
(150.0, 'mg')
...