0
我有一些代碼的代碼片段,我想抽象,只有有需要是動態的Django的蟒蛇EVAL
if myUser.profile.get_setting_c == True :
# below does not work but you get the idea, how
if myUser.profile.eval('get_setting_c') == True :
我有一些代碼的代碼片段,我想抽象,只有有需要是動態的Django的蟒蛇EVAL
if myUser.profile.get_setting_c == True :
# below does not work but you get the idea, how
if myUser.profile.eval('get_setting_c') == True :
一個小變化的函數這是你想要的嗎?
getattr(myUser.profile, 'get_setting_c')
BTW,使用eval
被認爲蟒蛇是不好的做法,看到Is using eval in Python a bad practice?。
爲什麼不
if eval('myUser.profile.get_setting_c') == True:
或
def fun(setting):
return eval('myUser.profile.%s' % setting)
if fun('get_setting_c') == True:
?
剛剛完成:分配給一個變量,如「attr = getattr(myUser.profile,'get_setting_c');如果attr == True:」 – diofeher 2011-12-20 02:22:06