Creating a class behaves like a bunch of keyword arguments in python

So, I have a class that will have many attributes. Is there a way to make this class behave in such a way that I can pass it as ** kwarg for the function?

class Foo ( object ) :
    def __init__( self ) :
         self.a = 'a'
         self.b = 'b'

foo = Foo()
somefunc(**foo)

I can not find the correct operator for overloading.

Thank you so much!

+3
source share
2 answers

**kwargsexpects a dictionary; the easiest way to support your class dict(ed: in addition to direct inheritance from dict, who also works) - inherit from collections.MutableMappingthat, you will need to determine __setitem__, __getitem__and __delitem__and give you the rest of the interface dictis free.

dict, __setattr__ __getattr__ . recipe, - , - , .

+2

, vars.

>>> def somefunc(**kwargs):
...     from pprint import pprint
...     pprint(kwargs)
...
>>> somefunc(**vars(foo))
{'a': 'a', 'b': 'b'}

- . vars .

0

Source: https://habr.com/ru/post/1757407/


All Articles