首页 > 解决方案 > 如何在类的构造函数中定义 *args

问题描述

我已经开始自学 Python,需要一些关于我目前正在处理的以下问题的建议。

  1. 在不知道要传递的参数总数的情况下,我应该如何使用构造函数方法。

我应该如何装饰计算器类的每个方法,使用记录争论的自定义方法。(使用自定义记录器方法)

如下所示:

The Input Values are : '10' '21' and '15'# 如果 *args 是 10、21 和 15

Operation : Multiply

我未完成的代码。

import logging


class Calculator:

    def add(self, *args):
        total = 0
        for val in args:
            total += int(val)
        return total

    def subtract(self, *args):
        total = 0
        for val in args:
            total -= val
        return total

    def multiply(self, *args):
        total = 1
        for val in args:
            total *= val
        return total

    def divide(self, *args):
        total = 1
        for val in args:
            total /= val
        return total

下面的操作给出了不正确的值:

print(Calculator.multiply(10, 2, 4))
print(Calculator.subtract(10, 2, 4))
print(Calculator.add(10,2,4))
print(Calculator.divide(10,2,4))

8
-6
6
0.125

标签: pythonpython-3.x

解决方案


有两个问题。

第一个问题是,您创建了一个类,因此您必须在使用它之前实例化一个对象:

calculator = Calculator()
print(calculator.multiply(10, 2, 4))
print(calculator.subtract(10, 2, 4))
print(calculator.add(10,2,4))
print(calculator.divide(10,2,4))

如果您键入Calculator.add(10,2,4)) ,则 10 将作为self且仅传递,2并且4将作为 传递args,因此args[2, 4]不是您的预期[10, 2, 4]

第二个问题是,substractdivide必须区别对待第一个参数。

所以以下应该工作:

import logging

logger = logging.getLogger(__name__)

class Calculator:

    def add(self, *args):
        logger.info("calc add %s", args)
        print("calc add ", args)
        total = 0
        for val in args:
            total += int(val)
        return total

    def subtract(self, *args):
        logger.info("calc subtract %s", args)
        print("calc substract ", args)
        if len(args) == 0:
            return 0
        total = args[0]
        for val in args[1:]:
            total -= val
        return total

    def multiply(self, *args):
        logger.info("calc multiply %s", args)
        print("calc multiply ", args)
        total = 1
        for val in args:
            total *= val
        return total

    def divide(self, *args):
        logger.info("calc divide %s", args)
        print("calc divide ", args)
        if len(args) == 0:
            return 1
        total = args[0]
        for val in args[1:]:
            total /= val
        return total


# Let's assume, that's the main function
logging.basicConfig(filename='example.log',level=logging.DEBUG)

calculator = Calculator()
print(calculator.multiply(10, 2, 4))
print(calculator.subtract(10, 2, 4))
print(calculator.add(10,2,4))
print(calculator.divide(10,2,4))

我添加了用于调试的打印语句。您当然必须将它们删除以进行“生产”

我将日志配置为将所有模块的级别为 DEBUG、INFO、WARNING、ERROR 和关键的所有日志写入日志文件。

根据您的用例,按照您的意愿设置日志记录可能会相当复杂。

https://docs.python.org/3.8/library/logging.html非常复杂,如果自由的话,会给你很多。这可能在一个单独的问题中得到更好的处理

附录:

关于__init__您在一条评论中询问的功能。

你可能想要一个计算器,它会记住上次计算的

在这种情况下,您将稍微更改您的代码。

你会添加一个__init__()方法

    def __init__(self):
        last_result = 0  # just some value

然后你必须改变multiply, subtract, ... 来存储最后的计算结果。

例如

    def add(self, *args):
        logger.info("calc add %s", args)
        print("calc add ", args)
        total = 0
        for val in args:
            total += int(val)
        self.last_result = total  # no you remember the last result.
        return total

如果你愿意,你现在可以检查最后的结果。和 print(calculator.last_result)

什么对计算器真正有意义?

也许是最后的n计算(操作 + 参数 + 结果)。

也许是一个内存和一个将最后一个结果添加或减去该内存的命令。


推荐阅读