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

前端 未结 10 1399
深忆病人
深忆病人 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:23

    Is there a better way to achieve similar convenience?

    I don't know if it is necessarily better, but you could do this:

    class Foo(object):
        def __init__(self, **kwargs):
            self.__dict__.update(kwargs)
    
    
    >>> foo = Foo(a = 1, b = 'bar', c = [1, 2])
    >>> foo.a
    1
    >>> foo.b
    'bar'
    >>> foo.c
    [1, 2]
    >>> 
    

    Courtesy Peter Norvig's Python: Infrequently Answered Questions.

提交回复
热议问题