python 试图在调用同一类的另一个方法的方法中的所有元素之间进行减法,以将它们相加

szqfcxe2  于 2023-06-04  发布在  Python
关注(0)|答案(1)|浏览(191)

我正在创建一个非常简单的Calculator类,并且我想创建一个能够独立工作的减法方法,或者至少在类本身指定的方法中。
问题是,对于减法,如果我使用-=,就像我使用+=进行加法一样,它将无法正常工作,并给予第一个数字减去起始值0。
该方法接受 *args,所以我可以给予任意多的数字,我现在试图使它接受第一个参数/数字作为默认值,然后减去其他数字的总和(使用我自己的加法方法)。
这是我到现在为止得到的代码:

class Calculator:
    """An attempt to create a calculator."""

    def __init__(self):
        self.current_value = 0

    # type hinting stuff:
    # https://stackoverflow.com/questions/50928592/mypy-type-hint-unionfloat-int-is-there-a-number-type
    def add(self, *args: float, reset=False):
        """
        Takes in a series of numbers as iterable and sums them up.

        If the iterable is empty, or has only one value, the function is invalid.

        :param args: Creates an iterable of any number. Can be `int` or `float`.
        :param reset: A boolean flag. If set to True, resets the current value to 0.
        :return: Return the sum of the 'start' value (default: 0) plus an iterable of numbers.
        """

        if reset:
            self.current_value = 0

        if len(args) >= 1:
            total = self.current_value
            for num in args:
                if isinstance(num, (int, float)):
                    total += num
                else:
                    print(f"Insert only valid numbers (integers or floats).  Try again...")

            self.current_value = total
            return total

        else:
            print(f"Insert at least one valid number (integer or float). Try again...")

    def subtract(self, *args: float, reset=True):
        """
        Takes in a series of numbers as iterable and subtracts them to the starting value of the first number.

        If the iterable is empty, the function returns 0.

        :param args: Creates an iterable of any number. Can be `int` or `float`.
        :param reset: A boolean flag. If set to True, resets the current value to 0.
        :return: Return the subtraction of the values inputted as iterables.
        """

        if reset:
            self.current_value = 0

        if len(args) >= 1:

            for num in args:
                if isinstance(num, (int, float)):
                    arg += num
                    continue
                else:
                    print(f"Insert only valid numbers (floats or integers). Try again...")
                    return None

            print(f'Current value: {self.current_value}')
            print(f'Sum of args', self.add(args))

            total = self.current_value - self.add(args)

            self.current_value = total
            return total

        else:
            print(f"Insert at least one valid number (integer or float). Try again...")

当前值用于保留先前操作的内存。因此,例如,如果我添加(5,2)= 7,然后调用subtract(3),它将是= 4,因为计算器的内存中存储了7,直到我手动重置它。

yquaqz18

yquaqz181#

数字相减和每个数字的负数相加是一样的。因此,您可以将subtract()简化为:

def subtract(self, *args: float, reset=True):
    return self.add(*(-arg for arg in args), reset=reset)

相关问题