1

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.

7
  • 1
    It looks as good as it'll get, really. It's just that this is inherently messy; classes are intended to hold stuff common to all instances, not depend on the latest one. Commented Sep 22, 2021 at 9:07
  • what's the use-case for this? Commented Sep 22, 2021 at 9:44
  • @yedpodtrzitko I need to import Example class in other file (module) to access the class variable of Example after a is instanced. Commented Sep 22, 2021 at 9:47
  • 1
    That's… still not very clear, and sounds potentially extremely yucky as far as OOP and sane program structure is concerned. Commented Sep 22, 2021 at 9:48
  • I have tried my best to make it OOP. The other classes need Example.d, Example.e and Example.f. Maybe there is other method to pass these variables. Commented Sep 22, 2021 at 9:50

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.