Need a cleaner way, which avoids too many 'if statements', to write this method for inputing data into datastore entity attributes?
What is the best way to reference datastore model attributes without using the four 'if statements'
I have in the below sample code, which seem messy and inefficient. For real-world code I may have a situation of 100 attributes such as self.var1, self.var2, ... self.varN
that I want to some how reference with just an integer (or strings) as an argument to some method.
c开发者_如何学Class PixelObject(db.Model):
zoom0 = db.ListProperty(int)
zoom1 = db.ListProperty(int)
zoom2 = db.ListProperty(int)
zoom3 = db.ListProperty(int)
zoom4 = db.ListProperty(int)
def inputZoomData(self, zoomInteger, input_data):
"""input_data goes to specified attribute based on if 0,1,2,3,or 4 is argument"""
if zoomInteger == 0: self.zoom0 = input_data
if zoomInteger == 1: self.zoom1 = input_data
if zoomInteger == 2: self.zoom2 = input_data
if zoomInteger == 3: self.zoom3 = input_data
if zoomInteger == 4: self.zoom4 = input_data
I'd also recommend using an array instead of five members to simplify your code:
if 0 <= zoomInteger < len(zooms):
self.zooms[zoomInteger] = input_data
else:
# Error handling.
If you can't change the way the class is designed another alternative is to use setattr
:
setattr(self, 'zoom' + str(zoomInteger), input_data)
How about using an array of integers, instead of holding five different integer properties?
精彩评论