OT (Kinda) Question

I have a class that accepts *args and **kwargs as it's initialization
parameters and I want to be able to set a class "property" for each of
the keywords, is there a way to do this?

#### Sudo-code Start ####
class Sample:
    def __init__(self, *args, **kwargs):
        for property in kwargs.keys():
            self.{property} = kwargs[property]

data = Sample(test='test1', more='more testing', int=7)

print data.test
#### Sudo-code End ####

You cannot define properties within the __init__ method, those need to
be defined when defining your class. But that's ok, I don't think you
meant what you said.

However, if you just want to set attributes, there are at least a couple
different ways:

    class Sample:
        def __init__(self, *args, **kwargs):
            self.__dict__.update(kwargs)

    class Sample:
        def __init__(self, *args, **kwargs):
            for i,j in kwargs.iteritems():
                setattr(self, i, j)

The latter should work in all cases, but the former won't work in the
following case...

    class Sample(object):
        __slots__ = ['test', 'more', 'int']
        def __init__(self, ...):
            ...

        other = property(...)

In the above example with __slots__ and properties, only the second
example using setattr will work, as the object has no __dict__.

- Josiah

···

"Dj Gilcrease" <digitalxero@gmail.com> wrote:

I have a class that accepts *args and **kwargs as it's initialization
parameters and I want to be able to set a class "property" for each of
the keywords, is there a way to do this?

#### Pseudo-code Start ####
class Sample:
    def __init__(self, *args, **kwargs):
        for property in kwargs.keys():
            self.{property} = kwargs[property]

data = Sample(test='test1', more='more testing', int=7)

print data.test
#### Pseudo-code End ####