2014-10-28 30 views
-1
class checkevent: 
def __init__(self,fromuser): 
self.fromuser = fromuser 

def openid_check(self):# use sqlalchemy 
    exist_user = User.query.filter_by(openid = self.fromuser).first() 
    if exist_user is None: 
     text = u'請綁定後在使用' 
     return text 

def grade(self): 
    openid_check() 
    exist_user = User.query.filter_by(openid = self.fromuser).first() 
    geturp = urp(exist_user.username, exist_user.password_urp) #the function 
    return geturp #return the grades as text 
def key_check(self,x): # use dict like switch 
    {'grade': self.grade 
     } 
contents = checkevent('ozvT4jlLObJWzz2JQ9EFsWSkdM9U').key_check('grade') 
print contents 

它總是返回無,我想要得到一個值 ,這是正確的方式來使用字典?使用像C開關字典

+0

'def key_check(self,x)'不返回任何東西。這就是爲什麼你得到'沒有'。另外你不要在函數中使用'x'。 – fredtantini 2014-10-28 14:26:52

回答

2

key_check中沒有return聲明,所以自然不會返回任何內容。你基本上缺少實現的最後一點:一旦你按名字查找適當的函數,你需要調用該函數並返回結果。

def key_check(self, key): # "x" is a meaningless name; use something meaningful 
    lookup = { 
     'grade': self.grade 
    } 
    func = lookup[key] # Look up the correct method 
    return func() # Call that method and return its result 

技術上你可以在線所有到一個說法,如果你真的想要,但除非業績寶貴,我不會因爲遭受可讀性推薦它。

+0

另一個問題,爲什麼我不能在等級函數中調用openid_check(),爲什麼字典使用像{'grade':self.grade}而不是{'grade':grade} – user3149621 2014-10-29 02:23:39

+0

'openid_check'和'grade'是兩個*實例方法*,所以你需要在實例('self')上調用它們。如果你對此有更多的疑問,這是一整個其他話題,有大量的在線資源(只是谷歌的「python實例方法」)。 – 2014-10-29 02:29:50