-3

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))
Kolibril
  • 1,096
  • 15
  • 19
  • Use an IDE. Pycharm should be able to do that. – rdas Jul 12 '20 at 09:15
  • When you just have numbers like 1,2,3,4 you don’t need anything different to your first snippet. – quamrana Jul 12 '20 at 09:17
  • My example is a minimal example for a more complicated case. I don't want my code to look like example 2, but only to behave like it. The reason: There are about 300 lines where I use a,b,c and I don't want to use every time `self. ` for reasons of readability – Kolibril Jul 12 '20 at 09:21
  • Perhaps you could change your minimal example to include more realistic variable types. At the moment you don’t need code like your second snippet. – quamrana Jul 12 '20 at 09:31
  • Ok, it's updated – Kolibril Jul 12 '20 at 09:37
  • 1
    I don't understand how the code in your "rich example" relates to your question. What is it you want to change in your code? – khelwood Jul 12 '20 at 09:38
  • Well, I don’t see the connection. When you have dot = Dot(), did you mean to do: self.dot = Dot() ? – quamrana Jul 12 '20 at 09:39
  • I want self.dot= dot and self.circ= circ – Kolibril Jul 12 '20 at 09:51

1 Answers1

1

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?

Adrien Kaczmarek
  • 530
  • 4
  • 13