Python initialization

I have this code:

def __init__(self, a, b, c, d...):
   self.a = a
   self.b = b
   etc

I am going to replace it:

def __init__(self, a, b, c, d...):
   args=locals()
   for key in args:
     self.__dict__[key] = args[key]

It is a bad idea? Are there any better ways to do this?

+5
source share
4 answers

Based on @ThiefMaster's comment about **kwargs:

If you accept 20 arguments, it might be necessary for your users to send arguments via the keyword instead of the position: with 20 arguments, there is a decent chance that someone using your code will receive the arguments in the wrong order.

Only consider accepting kwargs, having a predefined list of keys that you want to accept, and raising a ValueError if you haven't received them. That way you can use **kwargsand then verify that everything is there. For instance.

INITIAL_ARGS = set(['a','b','c','d','e'...])

def __init__(self, **kwargs):
    if not INITIAL_ARGS.issubset(set(kwargs.iterkeys())):
        raise ValueError("Class <myclass> requires 20 keyword arguments"
                          "only given %d" % len(kwargs))
    self.__dict__.update(kwargs)

, Pythonic, , , , , -, , .

+2

Zen of Python: , . .

, .

+9

. ? , , . , , . ThiefMaster, .

+1

Python3: init drastic.

@init
def __init__(self, a, b, c, d, e, f, g, h):
    # nothing to write here!
0

All Articles