I am trying to write a class object in python which has attributes which are closure functions able to modify a private string, I understand closures for the most part but I cannot get it to work with more than one. I am trying to return an array of function but i get
local variable 'string' referenced before assignment
indicating to me that either the string variable is destroyed or the functions are not retaining their closure status and being able to access it. The get_val function seems to work and I tried adding global declarations but either this is not the issue or I could not get it to work right.
class StringUpdater:
def _(self):
string = "MI"
def get_val():
return string
def add_u():
if string.endswith("I"):
string+="U"
def add_two_through_last():
string+=string[1:]
def replace_III_with_U():
#global string
string.replace("III", "U")
def remove_UU():
#global string
string.replace("UU", "")
return [get_val,add_u,add_two_through_last,replace_III_with_U,remove_UU]
def __init__(self):
str_obj = self._()
self.get_val = str_obj[0]
self.add_u = str_obj[1]
self.add_two_through_last = str_obj[2]
self.replace_III_with_U = str_obj[3]
self.remove_UU = str_obj[4]
f = StringUpdater()
print f.add_two_through_last()
print f.get_val()
string.)