0

I'm not sure if I'd be framing the question correctly but I'll try my best to explain my problem.

I have the code below where x and y are set to None in the beginning. In a new function, based on a condition, x and y are updated.

class problem()

    def __init__(self):

        self.x = None
        self.y = None

    def function(self):

        if some_condition:
           self.x = 10
           self.y = 5
        else:
           self.x = None
           self.y = None

The problem I have here is the total number of variables in __init__() are around 10 and all of these have to set to a value or reset back to original value based on the condition.

Is there a pythonic way to reset the variables back to original __init__() values when the if condition fails?

4
  • 6
    Why not have a reset method that's called from both places? Commented Nov 28, 2019 at 20:43
  • 1
    make an helper function that is called by both __init__ and function seems the soundest idea Commented Nov 28, 2019 at 20:43
  • 1
    maybe you could use a dictionary instead of variables. Less practical, but easier to reset. Commented Nov 28, 2019 at 20:44
  • Thank you for the comments. I created a reset method and called it from init and else condition. :) Commented Nov 28, 2019 at 21:14

1 Answer 1

2
class problem():

    def __init__(self):
        self.reset()

    def function(self):
        if self.x == None:
            self.x = 10
            self.y = 5
        else:
            self.x = None
            self.y = None

    def reset(self):
        self.x = None
        self.y = None

# These prints will help you understand how it works
per = problem()
per.function()
print(per.x, per.y)
per.reset()
print(per.x, per.y)

As easy as it looks like. I've entered reset() into init because it's just looks better. Also i'm highly recommend to check Corey Schafer's OOP Python tutorials, he explaining in best way i've heard.

Sign up to request clarification or add additional context in comments.

1 Comment

init should declare all attributes: softwareengineering.stackexchange.com/a/357941

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.