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

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

    This a simple implementation by judy2k:

    from inspect import signature
    
    def auto_args(f):
        sig = signature(f)  # Get a signature object for the target:
        def replacement(self, *args, **kwargs):
            # Parse the provided arguments using the target's signature:
            bound_args = sig.bind(self, *args, **kwargs)
            # Save away the arguments on `self`:
            for k, v in bound_args.arguments.items():
                if k != 'self':
                    setattr(self, k, v)
            # Call the actual constructor for anything else:
            f(self, *args, **kwargs)
        return replacement
    
    
    class MyClass:
        @auto_args
        def __init__(self, a, b, c=None):
            pass
    
    m = MyClass('A', 'B', 'C')
    print(m.__dict__)
    # {'a': 'A', 'b': 'B', 'c': 'C'}
    

提交回复
热议问题