简体   繁体   English

为什么 python 认为有 6 个位置 arguments 而我只有 5 个?

[英]Why does python think there are 6 positional arguments when I only have 5?

So I'm trying to use that Domino's pizza api with this program I'm making but I want to use user inputs instead of coded-in customer data.因此,我正在尝试将 Domino 披萨 api 与我正在制作的程序一起使用,但我想使用用户输入而不是编码的客户数据。 To do so, I coded this:为此,我编写了以下代码:

from pizzapi import Customer
address = input("Street Address: ") + ', ' + input('City: ') + ', ' + input('State Abbreviation: ') + ', ' + input('5-Digit Zip Code: ')
customer = Customer(input('First Name: '), input('Last Name: '), input('Email: '), input('Phone Number: '), str(address))
print(customer)

but when I try to run it, I get this error:但是当我尝试运行它时,出现了这个错误:

customer = Customer(input('First Name: '), input('Last Name: '), input('Email: '), input('Phone Number: '), str(address))
TypeError: Customer.__init__() takes from 1 to 5 positional arguments but 6 were given

How do I get rid of this error?我如何摆脱这个错误? I'm only inputting 5 parameters?我只输入 5 个参数?

edit: the customer module looks like this:编辑:客户模块如下所示:

class Customer:
    """The Customer who orders a pizza."""

    def __init__(self, fname='', lname='', email='', phone='', address=None):
        self.first_name = fname.strip()
        self.last_name = lname.strip()
        self.email = email.strip()
        self.phone = str(phone).strip()
        self.str_address = address
        self.address = Address(*address.split(','))

    def save(self, filename="customers/customer1.json"):
        """
        saves the current customer to a .json file for loading later
        """
        if not filename.startswith("customers"):
            filename = "customers/" + filename
        json_dict = {"first_name": self.first_name,
             "last_name": self.last_name,
             "email": self.email,
             "phone": self.phone,
             "address": self.str_address}

        with open(filename, "w") as f:
            json.dump(json_dict, f)

    @staticmethod
    def load(filename):
        """
        load and return a new customer object from a json file
        """
        with open(filename, "r") as f:
            data = json.load(f)

            customer = Customer(data["first_name"], 
                                data["last_name"],
                                data["email"],
                                data["phone"],
                                data["address"])
        return customer

    def __repr__(self):
        return "Name: {} {}\nEmail: {}\nPhone: {}\nAddress: {}".format(
            self.first_name,
            self.last_name,
            self.email,
            self.phone,
            self.address,
        )

You might need to force Python to load the latest definition of the module the class is in.您可能需要强制 Python 加载 class 所在模块的最新定义。

To be clear, Python says there are six arguments because it is counting the implicit self argument.要清楚, Python 表示有六个 arguments 因为它正在计算隐式self参数。

But the real strange thing is why it's saying it expects 1-5 arguments instead of 1-6.但真正奇怪的是为什么它说它期望 1-5 arguments 而不是 1-6。 The Customer definition you posted has the right number of parameters in the __init__ method that the error you're reporting wouldn't happen.您发布的Customer定义在__init__方法中具有正确数量的参数,因此您报告的错误不会发生。

This suggests that your Python process is using a different definition of Customer .这表明您的 Python 流程正在使用不同的Customer定义。 I can think of a few possibilities:我可以想到几种可能性:

  1. Make sure you save your changes to the pizzapi module file where you define Customer before running the code.在运行代码之前,请确保将更改保存到定义Customerpizzapi模块文件中。 (This might not be obvious if you are used to setups where you don't have to save code to try running it, but most IDEs for Python, and the raw python command itself, run the code you have saved, not the code as it is in your editor.) (如果您习惯于无需保存代码即可尝试运行的设置,这可能并不明显,但是大多数 Python 的 IDE 和原始python命令本身运行您保存的代码,而不是代码它在你的编辑器中。)

  2. There is a module with the same name in a different location which is being loaded first.在不同的位置有一个同名的模块首先被加载。 (Perhaps an older copy of pizzapi that you saved by making a copy?) (也许是您通过复制保存的旧pizzapi副本?)

  3. There is another import running later in your code which gets another Customer definition from a different module (a from example import * could do it, if the example module has a Customer defined).稍后在您的代码中运行另一个导入,它从另一个模块获取另一个Customer定义(如果example模块定义了Customer ,则from example import *可以做到这一点)。

  4. An older definition of the same module was already cached in the running Python process (such as when you use Jupyter/iPython, run python in a terminal to get a REPL, or have a little live Python panel in your IDE).同一模块的旧定义已缓存在正在运行的 Python 进程中(例如,当您使用 Jupyter/iPython 时,在终端中运行python以获得 REPL,或者在您的 IDE 中有一个小的实时 Python 面板)。

You can easily check the first problem: do import pizzapi and then print(pizzapi.__file__) .您可以轻松检查第一个问题:执行import pizzapi然后print(pizzapi.__file__) That will tell you what exact file path the pizzapi module is being loaded from.这将告诉您pizzapi模块从哪个确切的文件路径加载。 Check carefully if that's exactly the file that has your latest Customer definition.仔细检查这是否正是包含您最新Customer定义的文件。

The second is similarly easy to check: just run print(Customer.__module__) right before the customer = Customer(...) line.第二个同样容易检查:只需在customer = Customer(...)之前运行print(Customer.__module__) This will show you where the Customer being used in that line is coming from.这将向您显示该行中使用的Customer来自何处。

Once the first and second are ruled out or fixed, we get to the third one:一旦第一个和第二个被排除或固定,我们就得到第三个:

When a Python process runs import pizzapi or from pizzapi import Customer , it caches the definition of pizzapi .当 Python 进程运行import pizzapifrom pizzapi import Customer时,它会缓存pizzapi的定义。 After that, even if you change the definition of Customer , a second import pizzapi or from pizzapi import Customer will not pick up the changes.之后,即使您更改Customer的定义,第二个import pizzapifrom pizzapi import Customer不会获取更改。

One way to do this is to just quit the Python process and start over.一种方法是退出 Python 进程并重新开始。

Another way is to use importlib.reload :另一种方法是使用importlib.reload

  1. First make sure to run import pizzapi before the reload(pizzapi) if you haven't already.首先确保在reload(pizzapi)之前运行import pizzapi如果你还没有。

  2. Then do from importlib import reload and reload(pizzapi) .然后执行from importlib import reloadreload(pizzapi)

  3. Finally, you'll need to re-run imports of specific things from the module such as from pizzapi import Customer .最后,您需要从模块重新运行特定内容的导入,例如from pizzapi import Customer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在 python 3.8 中只使用位置 arguments? - Why use positional only arguments in python 3.8? 当只有 3 个参数时,为什么 python 说有 4 个参数? - Why does python say there are 4 arguments when there are only 3? 为什么Python在我认为文件不存在时会认为该文件不存在? - Why would Python think a file doesn't exist when I think it does? 为什么我在 Python 中传递 function 时缺少必需的位置 arguments? - Why am I missing required positional arguments when passing a function in Python? 当我只提出一个论据时,为什么会有两个论据呢? - How come there are two positional arguments when I put only one? 为什么我的Python类声称我有2个参数而不是1? - Why does my Python class claim that I have 2 arguments instead of 1? 什么时候在我的Python程序中使用位置参数? - When would I use positional arguments for my Python program? 为什么 lambda 返回“<lambda> () 取 0 位置 arguments 但给出 1”当我给出位置参数时?</lambda> - Why is lambda returning "<lambda>() takes 0 positional arguments but 1 was given" when I gave a positional argument? 是否有任何标准的Python3对象具有不带位置参数的get方法? - Does any standard Python3 object have a get method that doesn't have positional arguments? 为什么 Python 在尝试强制转换时认为我正在创建一个变量? - Why does Python think I'm creating a variable when trying to cast?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM