Skip to main content
 首页 » 编程设计

python之根据用户输入创建对象

2025年05月04日15bhlsheji

我有几个问题。下面的代码没有运行,因为我已经为 __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() 创建实例时会发现这个问题。

请您参考如下方法:

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

d = Dog(**make_dog()) 

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

另见 Unpacking Argument Lists在官方 Python 教程中。