【问题标题】:Creating objects based on user input根据用户输入创建对象
【发布时间】:2018-03-12 23:45:03
【问题描述】:

我有几个问题。下面的代码没有运行,因为我为__init__ 方法指定了三个参数,而make_dog 函数返回一个字典。

class Dog():
    def __init__(self, name, colour, sex):
        self._name = name
        self._colour = colour
        self._sex = sex

    def __str__(self):
        return '{}, {}, {}'.format(self._name, self._colour, self._sex)

def make_dog():
    user_dog = {}
    yes_or_no = input('Would you like to make a dog?! ')
    if 'y' in yes_or_no:
        print('Great! Let\'s get started')
        user_dog['name'] = input('What shall we call the dog: ')
        user_dog['colour'] = input('What colour is the dog: ')
        user_dog['sex'] = input('What sex is the dog: ')
        return user_dog
    else:
        print('Come back when you want to make a dog. Bye...')
        exit()

d = Dog(make_dog())
print(d)

这是输出:

Would you like to make a dog?! y
Great! Let's get started
What shall we call the dog: doggie
What colour is the dog: white
What sex is the dog: male
Traceback (most recent call last):
  File "test.py", line 25, in <module>
    d = Dog(make_dog())
TypeError: __init__() missing 2 required positional arguments: 'colour' and 'sex'
  1. 根据用户输入创建狗的最佳/标准方法是什么?

  2. 使用make_dog 函数中的字典是一种推荐的存储和返回函数值的方法吗?我认为是,但想检查一下。

非常感谢。

编辑:我不认为这是 Passing a dictionary to a function in python as keyword parameters 的重复,因为我认为我的问题更加以初学者为中心和具体。希望其他初学者在想知道如何使用input() 创建实例时会发现这个问题。

【问题讨论】:

  • 我同意“将字典作为关键字参数传递给 python 中的函数”可能适合初学者,如果没有,我不会期望你找到它知道你在找什么。即使那样,如果没有进一步的解释,它也可能对您没有太大帮助。这就是为什么我对回答你的问题并不感到内疚,而不是简单地将其作为副本关闭。 :)
  • kirsty,这是对@PM2Ring 链接的帖子的欺骗。此外,重复的帖子一点也不差。请记住,正如您所说的初学者可能会找到您的帖子,初学者也可能对链接的帖子感兴趣。也就是说,如果作为骗子关闭并且有人看到另一个帖子,他们可能会回来查看您的帖子,因为它将位于另一个问题的链接帖子部分。我希望你能理解:-)
  • 对不起。该消息建议编辑我的问题,以解释为什么它不是由 PM 2Ring 链接的问题。

标签: python python-3.x


【解决方案1】:

是的,您可以这样做,但是您必须使用** 运算符将dict 转换为参数列表。

d = Dog(**make_dog())

请参阅What does ** (double star) and * (star) do for Python parameters? 了解更多信息。

另见官方 Python 教程中的Unpacking Argument Lists

【讨论】:

  • 谢谢。如果不是这种方式,那么“正常”的方式是什么?
  • @kirstyhattersley:恕我直言,你正在做的事情没问题。但是看看链接问题的答案,它应该会给你更多的想法。
  • 是的。非常感谢!
【解决方案2】:

正如所写,该类无法解压缩您的字典。你可以替换这一行

d = Dog(make_dog())

user_dog = make_dog()
d = Dog(user_dog['name'], user_dog['colour'], user_dog['sex']

也就是说,这有点乱。您可能甚至不应该首先打扰字典。而且您可能应该在函数中创建 dog 对象。

【讨论】:

    【解决方案3】:

    您的函数返回一个字典,并且类应该包含参数。使用

    **dict 或 **func()

    在新的对象调用中

    【讨论】:

      【解决方案4】:

      请看看这是否符合您的要求。

      它允许实时用户输入来设置属性。

      https://stackoverflow.com/a/69235456/16829896

      【讨论】:

        猜你喜欢
        • 2021-11-18
        • 2017-09-11
        • 1970-01-01
        • 2020-03-14
        • 2015-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多