7

Python classes have an initializer method called init. Frequently the initializer accepts several arguments that are copied to eponymous attributes.

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

This is a lot of work and feels "unpythonic" to me. Is there a way to automate the process?

I thought maybe something along these lines (pseudocode below) could work:

for x in __init__.argument_names:
    exec('self.' + x + ' = ' + x)

I know calling exec in this way would not be good practice. But maybe the Python development team has created a safe and equivalent way of automating this task.

Any suggestions?

FS

2
  • While there are ways to do this, they are generally bad ideas, prone to breaking. They tie the argument names and attribute names too closely together, and they tend to interact poorly with descriptors, __setattr__, or __slots__. Best practice is usually to just set all the attributes manually. Commented Aug 17, 2013 at 17:54
  • Does this answer your question? How to properly set Python class attributes from init arguments Commented Feb 19, 2022 at 22:16

2 Answers 2

4

You can achieve this using inspect module (EDIT: as correctly pointed out in comments, you actually don't need to import this module):

class A:
    def __init__(self, a, b, c, d):
        args = locals().copy()
        del args['self']
        self.__dict__.update(args)

a = A(1,2,3,4)
print a.a
print a.b
print a.c
print a.d

python test.py
1
2
3
4

You could wrap this into an utility function, just remembering not to take currentframe but getouterframes.

Sign up to request clarification or add additional context in comments.

3 Comments

Don't modify the locals dict. Copy it if you really want to do that. (Also, why all the inspect stuff instead of just locals()?)
self.__dict__.update((k, v) for k, v in locals().iteritems() if k != 'self') makes the .copy() call unnecessary.
Yeah, a loop with if was the previous version (without the comprehension though) but this seems more readable. Your version is a good alternative of course.
1

Here's a way to do it:

class test:
    def __init__(self, *args):
        names = ['a', 'b', 'c', 'd']
        for name, arg in zip(names, args):
            setattr(self, name, arg)

t = test(5, 6, 7, 8)
print t.a, t.b, t.c, t.d
# 5 6 7 8

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.