What is the best way to do automatic attribute assignment in Python, and is it a good idea?

前端 未结 10 1381
深忆病人
深忆病人 2020-11-30 00:00

Instead of writing code like this every time I define a class:

class Foo(object): 
     def __init__(self, a, b, c, d, e, f, g):
        self.a = a
        s         


        
相关标签:
10条回答
  • 2020-11-30 00:32

    If you have a lot of variables, you could pass one single configuration dict or object.

    0 讨论(0)
  • 2020-11-30 00:33

    Similar to the above, though not the same... the following is very short, deals with args and kwargs:

    def autoassign(lcls):
        for key in lcls.keys():
            if key!="self":
                lcls["self"].__dict__[key]=lcls[key]
    

    Use like this:

    class Test(object):
        def __init__(self, a, b, *args, **kwargs):
            autoassign(locals())
    
    0 讨论(0)
  • 2020-11-30 00:33

    In this package you can now find

    • @autoargs inspired by answer-3653049
    • @autoprops to transform the fields generated by @autoargs into @property, for use in combination with a validation library such as enforce or pycontracts.

    Note that this has been validated for python 3.5+

    0 讨论(0)
  • 2020-11-30 00:36

    From Python 3.7+ you can use a Data Class, which achieves what you want and more.

    It allows you to define fields for your class, which are attributes automatically assigned.

    It would look something like that:

    @dataclass
    class Foo:
        a: str
        b: int
        c: str
        ...
    

    The __init__ method will be automatically created in your class, and it will assign the arguments of instance creation to those attributes (and validate the arguments).

    Note that here type hinting is required, that is why I have used int and str in the example. If you don't know the type of your field, you can use Any from the typing module.

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