i trying add value instance list in python want access dynamically within method.
i cannot use dictionaries trying speed sorting of separate lists (boxes) rather 1 large list.
can show me correct way following?
class boxes: def __init__(self): self.box1 = [] self.box2 = [] #.... self.box10 = [] def addtobox(self, value): box = self.determineboxtouse(value) ## box = 2 varname = "box", box ## box2 self.varname.insert(0, value) def determineboxtouse(self, value): ## example returns 2 return 2 def dumpbox(self): print self.box2 boxes = boxes(); boxes.addtobox("123.001234") boxes.dumpbox()
error: attributeerror: boxes instance has no attribute 'varname'
thanks
you can use hasattr
, getattr
, although many might suggest should pursue different solution.
def addtobox(self, value): box = self.determineboxtouse(value) ## box = 2 varname = "box{}".format(box) ## box2 if hasattr(self, varname): getattr(self, varname).insert(0,value)
demo:
>>> class boxes: def __init__(self): self.box1 = [] self.box2 = [] #.... self.box10 = [] def addtobox(self, value): box = self.determineboxtouse(value) ## box = 2 varname = "box{}".format(box) ## box2 if hasattr(self, varname): getattr(self, varname).insert(0,value) def determineboxtouse(self, value): ## example returns 2 return 2 def dumpbox(self): print self.box2 >>> boxes = boxes() >>> boxes.addtobox("123.001234") >>> boxes.dumpbox() ['123.001234'] >>>