Home > Software engineering >  Python create instance attributes by kwargs
Python create instance attributes by kwargs

Time:09-19

Need help with a little problem here. I want to create instance attributes from the input to a class __init__ method.

class Test():
    def __init__(self, *args, **kwargs):
        """Create instance attributes from dict"""


t = Test(a=1, b=2, c=3)

print(t.a, t.b, t.c)

CodePudding user response:

kwargs is a dictionary and you can set class attributes from a dictionary using self.__dict__:

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

t = Test(a=1, b=2, c=3)
print(t.a, t.b, t.c)

Output:

1 2 3

CodePudding user response:

Using self.__setattr__():

class Test:
    def __init__(self, *args, **kwargs):
        for key, val in kwargs.items():
            self.__setattr__(key, val)


t = Test(a=1, b=2, c=3)

print(t.a, t.b, t.c)
# 1 2 3

CodePudding user response:

Iterate over kwargs and set attributes by calling setattr():

class MyClass:
    def __init__(self, *args, **kwargs):
        """Create instance attributes from dict"""
        for key, value in kwargs.items():
            setattr(self, key, value)
    
t = Test(a=1, b=2, c=3)

print(t.a, t.b, t.c)

Check here for more details about setattr() method in Python.

Check here for more details about Python **kwargs.

CodePudding user response:

The setattr function is the friend you're looking for:

class Test:
    def __init__(self, *args, **kwargs):
        for k, v in kwargs.items():
            self.__setattr__(k, v)

t = Test(1, b=2, c=3)

print(t.a, t.b, t.c)

Result:

1 2 3

In more complex code, you might not want to assign all of the key/value pairs in **kwargs as instance attributes, and you might want to be sure that the caller provides some required values. You could make the params explicit and still get the behavior you want, with something like:

class Test:
    def __init__(self, a, b, *args, **kwargs):
        self.__setattr__('a', a)
        self.__setattr__('b', b)
        if 'c' in kwargs:
            self.__setattr__('c', kwargs['c'])

t = Test(1, 2, c=3)

print(t.a, t.b, t.c)

Same result:

1 2 3

CodePudding user response:

I'll fill in what you're missing here:

class Test:

    def __init__(self, *args, **kwargs):
    """Create instance attributes from dict"""
        self.a = kwargs["a"]
        self.b = kwargs["b"]
        self.c = kwargs["c"]

t = Test(a=1, b=2, c=3)
print(t.a, t.b, t.c)
  • Related