Python Forum
User-defined function to reset variables? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: User-defined function to reset variables? (/thread-37302.html)



User-defined function to reset variables? - Mark17 - May-25-2022

Hi all,

A general outline of my program could be written as something like this:

Variable initiation (reset)

Control branch A

    if...

    elif...

    elif...

    else...
        ...
        Variable reset

Control branch B

    if...

    elif...

    else...
        ...
        Variable reset
Variable initiation and reset simply assign particular variables to 0, empty lists, etc. Because it's done in multiple places, I'm thinking about creating a user-defined function where the variables common to all three places are reset to 0.

If I were to do such a thing, how would I handle variable scope? The variables reset in the function need to be available throughout the main program.

Finally, do you think this is even worth doing?

I have ~50 variables in this program and maybe 30 would be reset as part of the function.


RE: User-defined function to reset variables? - Gribouillis - May-25-2022

(May-25-2022, 02:31 PM)Mark17 Wrote: I'm thinking about creating a user-defined function where the variables common to all three places are reset to 0.
This is why classes were invented: to group in a single entity variables shared by different places. So create a class (or several classes) to hold the variables
class Foo:
    def __init__(self):
        self.reset()

    def reset(self):
        self.baz = 10
        self.bar = 'hello'
        self.spam = 3.14159

foo = Foo()
...
...
if ...:
    ...
    foo.reset()



RE: User-defined function to reset variables? - Mark17 - May-25-2022

(May-25-2022, 03:05 PM)Gribouillis Wrote: This is why classes were invented: to group in a single entity variables shared by different places. So create a class (or several classes) to hold the variables

I've studied some intro stuff about classes, but they really confuse me (along with all the syntax like the __init__, the self, etc.). Can you explain this in a simpler way? If I clearly understand their place and am convinced it's worth doing, then I'll force myself through it and figure it out.


RE: User-defined function to reset variables? - Gribouillis - May-25-2022

(May-25-2022, 07:14 PM)Mark17 Wrote: If I clearly understand their place and am convinced it's worth doing
Decades of progress in programming and generations of top-level engineers tell you it's worth doing. There is absolutely no reason to hesitate: learn classes as soon as possible. Start with chapter 9 of the official Python Tutorial for an introduction.