【发布时间】: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'
根据用户输入创建狗的最佳/标准方法是什么?
使用
make_dog函数中的字典是一种推荐的存储和返回函数值的方法吗?我认为是,但想检查一下。
非常感谢。
编辑:我不认为这是 Passing a dictionary to a function in python as keyword parameters 的重复,因为我认为我的问题更加以初学者为中心和具体。希望其他初学者在想知道如何使用input() 创建实例时会发现这个问题。
【问题讨论】:
-
我同意“将字典作为关键字参数传递给 python 中的函数”可能不适合初学者,如果没有,我不会期望你找到它知道你在找什么。即使那样,如果没有进一步的解释,它也可能对您没有太大帮助。这就是为什么我对回答你的问题并不感到内疚,而不是简单地将其作为副本关闭。 :)
-
kirsty,这是对@PM2Ring 链接的帖子的欺骗。此外,重复的帖子一点也不差。请记住,正如您所说的初学者可能会找到您的帖子,初学者也可能对链接的帖子感兴趣。也就是说,如果作为骗子关闭并且有人看到另一个帖子,他们可能会回来查看您的帖子,因为它将位于另一个问题的链接帖子部分。我希望你能理解:-)
-
对不起。该消息建议编辑我的问题,以解释为什么它不是由 PM 2Ring 链接的问题。
标签: python python-3.x