Creating objects based on user input

后端 未结 3 732
轮回少年
轮回少年 2021-01-27 03:37

I have a couple of questions. The code below doesn\'t run because I\'ve specified three arguments to the __init__ method and the make_dog function retu

相关标签:
3条回答
  • 2021-01-27 03:52

    Yes, you can do this, but you have to use the ** operator to convert the dict to an argument list.

    d = Dog(**make_dog())
    

    Please see What does ** (double star) and * (star) do for Python parameters? for further info.

    Also see Unpacking Argument Lists in the official Python tutorial.

    0 讨论(0)
  • 2021-01-27 04:03

    Your function returns a dicitionary and class should takie argunents. Use

    **dict or **func()

    in a new object call

    0 讨论(0)
  • 2021-01-27 04:11

    As written, the class can't unpack your dictionary. You could replace this line

    d = Dog(make_dog())
    

    With

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

    That said, it's kind of messy. You probably shouldn't even bother with the dictionary in the first place. And you should probably create the dog object within the function.

    0 讨论(0)
提交回复
热议问题