根据用户输入创建对象

时间:2016-02-13 13:22:56

标签: python python-3.x

我有几个问题。下面的代码没有运行,因为我已经为__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函数中的字典作为存储和返回函数值的推荐方法?我认为这只是想检查一下。

  3. 非常感谢。

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

3 个答案:

答案 0 :(得分:5)

是的,您可以执行此操作,但您必须使用**运算符将dict转换为参数列表。

d = Dog(**make_dog())

有关详细信息,请参阅What does ** (double star) and * (star) do for Python parameters?

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

答案 1 :(得分:1)

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

d = Dog(make_dog())

使用

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

那就是说,它有点乱。你可能不应该首先打扰字典。你应该在函数中创建dog对象。

答案 2 :(得分:0)

你的函数返回一个dicitionary和类应该takie argunents。使用

  

** dict或** func()

在新的对象调用中