Search code examples
pythonclassselfmanim

Automatically transform all variables in a class to "self" variables


My code (minimal example) looks like this:

class Hello:
    a=1
    b=2
    c=3
    def __init__(self):
        self.d= 4

and I am searching for a function like set_all_vars_to_self_vars() which I can call in the class Hello, so that the Hello class becomes equvilent to:

class Hello:
    def __init__(self):
        self.d = 4
        self.a = 1
        self.b = 2
        self.c = 3

Is there some functionality that does that?

The rich example looks like this:

from manim import *

class Scene1(Scene):
    def construct(self):
        dot = Dot()
        circ= Circle()
        self.add(dot,circ)
        self.set_variables_as_attrs(dot)  # at the moment, variables have to be added manually
        return self

class Scene2(Scene):
    def construct(self):
        sc1 = Scene1.construct(self)
        dot2= Dot().next_to(sc1.dot)
        self.play(ShowCreation(dot2))

Solution

  • Variables you define outside the __init__ are not at all comparable with these you declare inside the __init__. The first ones belong to the Class, the second ones belong the the Object.

    Thus, if you want a, b, c and d to change with each instance of Hello(), you should not declare them outside the scope of the __init__(). They simply do not have the same meaning.

    However, if it is what you want to do, here is how to do this:

    class Hello:
        a = 4
        b = 4
        c = 4
    
        def __init__(self):
            d = 4
            for attr in dir(self):
                if not callable(attr) and not attr.startwith('__'):
                    self.__dict__.setdefault(attr, Hello.__dict__.get(attr))
    

    Then, with H = Hello() you will have, for example, H.a = Hello.a. More generally, you will have a copy of each variable of the Class for each Instance of your Class.

    Is this want you wanted?