开发者

making a class behave like a bunch of keyword arguments in python

开发者 https://www.devze.com 2023-01-10 03:05 出处:网络
So I have a class that will have a lot of attributes. Is there a way to make this class behave in a way that I can pass it as a **kwarg to a function?

So I have a class that will have a lot of attributes. Is there a way to make this class behave in a way that I can pass it as a **kwarg to a function?

class Foo ( object ) :
    def __init__( self ) :
         self.a = 'a'
        开发者_如何转开发 self.b = 'b'

foo = Foo()
somefunc(**foo)

I cannot find the right operator to overload.

Thanks a lot!


**kwargs expects a dictionary; the easiest way to make your class support dict operations (ed: apart from directly inheriting from dict, which also works) is to inherit from the collections.MutableMapping mixin, which will need you to define __setitem__, __getitem__ and __delitem__ and give you the rest of the dict interface for free.

You can keep an internal dict of attributes, pass those three functions through to it, and additionally implement __setattr__ and __getattr__ to support attribute-style access. Here's a recipe that does something like what you're looking for - you need to be careful about messing with those two.


I think what you want is vars.

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

No need to overload anything this way. vars is a builtin.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号