Search code examples
pythonclass-method

Fast way to initialize class variables in Python


I would like to initialize an instance and let both args and kwargs become class variables.

class Example():
    def __init__(
        self,
        a: str,
        b: bool,
        c: int,
        d="str",
        e=True,
        f=123,
    ):
        class_member = dict(locals())
        del class_member["self"]
        self.set_property(class_member)

    @classmethod
    def set_property(cls, kwargs):
        for key, value in kwargs.items():
            setattr(cls, key, value)

a = Example("test", True, 1, d="test", e=False, f=456)
print(Example.d)  # test

I have searched a lot and get the above result.

Is there any other cleaner way to deal with that? Thanks!

--Edit--

Thanks for all answers. My simplified version:

class Example():
    def __init__(
        self,
        a: str,
        b: bool,
        c: int,
        d="str",
        e=True,
        f=123,
    ):
        class_member = dict(locals())
        del class_member["self"]
        for key, value in class_member.items():
            setattr(Example, key, value)

a = Example("test", True, 1, d="test", e=False, f=456)
print(Example.d)  # test

I had thought about using **kwarg previously, but I still need to assign default value for kwargs. So this is my final solution.


Solution

  • You could use setattr and kwargs only:

    class Example:
        def __init__(self, **kwargs):
            for k, v in kwargs.items():
                setattr(Example, k, v)
    
    
    a = Example(a="test", b=True, c=1, d="test", e=False, f=456)
    print(Example.d)  # test