开发者

learn python the hard way exercise 40 help

hey guys i am having trouble understanding this, i dont get when themap is referenced to the cities dict really. or the last line, what is the(cities, state) part?

thanks.

cities = { 'CA': 'S开发者_运维问答an Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'}

cities['NY'] = 'New York'
cities['OR'] = 'Portland'

def find_city(themap, state):
    if state in themap:
        return themap[state]
    else:
        return 'not found'

#ok pay attention!
cities['_find'] = find_city

while True:
    print 'State? (ENTER to quit)'
    state = raw_input('> ')

    if not state: break

    #this line is the most important ever! study!
    city_found = cities['_find'] (cities, state)
    print city_found


cities['_find'] is exactly find_city. So cities['_find'](cities, state) is the same as find_city(cities, state).

The reason for my first statement is this line:

cities['_find'] = find_city

That doesn't call find_city, it sticks the function itself in the dictionary. Python functions are just objects like lists and class instances. If you don't put parentheses after them, they can be assigned to variables.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜