0

I want to create a class where the attributes of its instance are defined at instantiation.

At first I thought I should do something like this,

class TestData(object):  # Example via http://stackoverflow.com/questions/2641484/class-dict-self-init-args

    def __init__(self, *args, **kwargs):
        super(TestData, self).__init__()
        for arg in args:
            self.arg = arg

but that would assign all arguments to the same attribute self.arg and that wont work.

Paul H
  • 901
  • 2
  • 7
  • 12

1 Answers1

0

Modified with suggestions from comments, I came to this solution which works for me:

class TestData(object):  # Example via http://stackoverflow.com/questions/2641484/class-dict-self-init-args

    def __init__(self, *args, **kwargs):
        super(TestData, self).__init__()
        self.__dict__.update(kwargs)
        for arg in args:
            setattr(self, arg, arg)

and if further attributes need to be added subsequent to instantiation, that can be done by calling setattr(instancename, arg, val)

Paul H
  • 901
  • 2
  • 7
  • 12
  • Now I'd like to find out how to define a class method to call which would easily print out all the attributes. – Paul H Apr 21 '14 at 16:20
  • 1
    There is no need to call `__setattr__` in either case. Generally you should avoid calling the double-underscore magic methods directly. Just do `setattr(self, arg, arg)`. – Daniel Roseman Apr 21 '14 at 16:54
  • 1
    instead of overwriting the __dict__ it's better to update it: `self.__dict__.update(**kwargs)`. – Daniel Apr 21 '14 at 17:15