How to reset a class within a loop in Python?

Viewed 27

I'm making a Hang Man game as a side project in python and came across a problem when trying to reset a class called "Hanger" in a while loop. Essentially what would happen is I would have a class instance defined inside of a while loop. At the end of the while loop I would "delete" the instance, then re-make the instance when the while loop re-iterated.

class ExampleHanger:
    # Hanger
    row0 = "______"
    row1 = "|    {}"
    row2 = "|   {}{}{}"
    row3 = "|  {}{} {}{}"
    spine = "|"
    bottom = spine + row0
    hanger = [row0, row1, row2, row3, spine, bottom]

    body = {'head': 'o','spine': '|','left_limb': '/','right_limb': '\\','foot': '_'}
    body_count = ['head','left_limb','spine','right_limb','foot','left_limb','right_limb','foot']
    def __init__(self):
        self.hanger = hanger
        self.body = body
        self.body_count = body_count
        self.row1 = row1
        self.row2 = row2
        self.row3 = row3

The class above contains the original attributes I want to "reset" to.

Within this while loop, I instantiate the class then delete it at the end of the while loop to try and reset it for the next iteration of the loop.

while True:
    hanger = ExampleHanger()
    # 
    # Logic of the game
    #
    del hanger
    continue

The main problem is that the attributes of the class would not reset when deleting and making another instance, essentially calling the innit function again but not having the attributes reset to the original "rows" that I implemented, instead, sticking with the formatted version of the hanger with the body on it.

How could I reset the instance of the class or delete it and re-instantiate it all within the while loop so that the attributes go back to what the class defined them as (that being the empty curly braces)?

1 Answers

The answer I found was to create reset method inside the class and call it inside the __init__ method, that way we can define the class instance outside of the loop:

class Hanger:
    
    def __init__(self):
        self.reset()

    # Other display and hanging methods for the hanger

    def reset(self):
        #define all the attributes

This way, the attributes are properly reset by just calling that reset function.

hanger = Hanger
while True:
    # all the logic of the game
    # asks the user to play again, if yes, then:
    hanger.reset()
    continue
    
Related