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