Passing dict to constructor?

后端 未结 3 1740
攒了一身酷
攒了一身酷 2021-01-01 18:55

I\'d like to pass a dict to an object\'s constructor for use as kwargs.

Obviously:

foo = SomeClass(mydict)

Simply passes a single

相关标签:
3条回答
  • 2021-01-01 19:14

    Try this: SomeClass(**mydict)

    0 讨论(0)
  • 2021-01-01 19:23

    Use :

    foo = SomeClass(**mydict)
    

    this will unpack the dict value and pass them to the function.

    For example:

    mydict = {'a': 1, 'b': 2}
    
    SomeClass(**mydict) # Equivalent to : SomeClass(a=1, b=2)
    
    0 讨论(0)
  • 2021-01-01 19:30

    To pass a dictionary to a constructor you have to do so by reference, which is by preceding it with **, like so:

    foo = SomeClass(**mydict)
    
    0 讨论(0)
提交回复
热议问题