【问题标题】:Python: How to pass a function containing a dictionary to another function?Python:如何将包含字典的函数传递给另一个函数?
【发布时间】:2012-05-10 07:41:29
【问题描述】:

我是 python 新手,我正在开发一个游戏来自学 python。这场比赛将有许多课程,有问题和答案;用户将根据其答案的有效性获得和失去积分。

我正在使用字典来存储将在每节课中提出的问题和答案。

我只想在特定点(例如,在用户输入命令后)显示和检查字典的键和值。为此,我想我可以创建包含字典的函数,然后在需要时将它们传递给主函数。

但是当我运行下面的代码时,我得到了以下错误:AttributeError: 'function' object has no attribute 'iteritems'

所以我有两个问题:

  1. 我尝试从函数中删除字典,它可以工作 那么就好了。有什么办法(或理由)让它在 一个函数?
  2. 是否可以只使用一个字典并在某些点检查其中一部分的键和值?

到目前为止,这是我的代码。任何建议将不胜感激!

points = 10 # user begins game with 10 pts 

def point_system(): 
    global points

    #help user track points
    if 5 >= points: 
        print "Careful. You have %d points left." % points 
    elif points == 0: 
        dead("You've lost all your points. Please start over.")
    else:
        print "Good job. Spend your points wisely." 

def lesson1(): 
    #create a dictionary 
    mydict = {
    "q1":"a1", 
    "q2":"a2"
    }

return mydict

def main(lesson):
    global points

    #get key:value pair from dictionary
    for k, v in lesson.iteritems():
        lesson.get(k,v) # Is the .get step necessary? It works perfectly well without it.
        print k
        user_answer = raw_input("What's your answer?: ") 

#test if user_answer == value in dictionary, and award points accordingly 
        if user_answer == v:
            user_answer = True
            points += 1 #increase points by 1 
            print "Congrats, you gained a point! You now have %d points" % points 
            point_system()
        elif user_answer != v: 
            points -= 1 #decrease points by 1 
            print "Oops, you lost a point. You now have %d points" % points 
            point_system()
        else: 
            print "Something went wrong."
            point_system()


main(lesson1) 

以及有效的代码:

points = 10 # user begins game with 10 pts 

#create a dictionary 
lesson1 = {
"q1":"a1", 
"q2":"a2"
}

def point_system(): 
    global points

    #help user track points
    if 5 >= points: 
    print "Careful. You have %d points left." % points 
    elif points == 0: 
    dead("You've lost all your points. Please start over.")
    else:
    print "Good job. Spend your points wisely." 

def main(lesson):
    global points

    #get key:value pair from dictionary
    for k, v in lesson.iteritems():
        lesson.get(k,v) # Is the .get step necessary? It works perfectly well without it.
        print k
        user_answer = raw_input("What's your answer?: ") 

#test if user_answer == value in dictionary, and award points accordingly 
        if user_answer == v:
            user_answer = True
            points += 1 #increase points by 1 
            print "Congrats, you gained a point! You now have %d points" % points 
            point_system()
        elif user_answer != v: 
            points -= 1 #decrease points by 1 
            print "Oops, you lost a point. You now have %d points" % points 
            point_system()
        else: 
            print "Something went wrong."
            point_system()


main(lesson1) 

【问题讨论】:

  • 我认为你需要在这里尝试OOP approach
  • 只是好奇...你是 javascript 程序员吗?
  • 感谢您的参考,@DrTyrsa。
  • @parselmouth,是的,我是从 javascript 开始的——为什么?
  • @user1186742 您的课程 1() 函数有点像用于生成新对象的 javascript 工厂函数。我想我会问你的 javascript 经验,因为知道你来自 javascript 背景,我们这些同时了解 javascript 和 python 的人可以更好地向你展示 python 如何以不同的方式做某些事情以及为什么。无论如何 - 欢迎来到 python 社区! Python 是一门了不起的语言,我希望您会发现自己喜欢使用它并且使用它非常高效。

标签: python function dictionary arguments


【解决方案1】:

您正在使用第 1 课函数调用 main(),而不是第 1 课函数(它是一个目录)的结果。

你应该写:

main(lesson1())

顺便说一句,第 1 课还必须返回创建的目录才能正常工作:

def lesson1(): 
    #create a dictionary 
    mydict = {
        "q1":"a1", 
        "q2":"a2"
    }
    return mydict

【讨论】:

  • 将字典放在函数中是最佳做法,还是将它放在外面也一样?
【解决方案2】:

您传递了一个返回字典的函数,因此您应该首先调用该函数来获取字典。所以你可以修改你的代码,以便 main 接受字典(代码实际上需要一个字典):

main(lesson1())

如果你真的想传递一个函数,那么你应该修改你main以先执行函数来获取字典:

def main(lessonFunc):
    global points
    lesson = lessonFunc()

    #get key:value pair from dictionary
    for k, v in lesson.iteritems():

但第一个选项可能更好。您还可以将课程打包到一个对象中。

【讨论】:

  • 感谢您的解释。将课程打包到对象中有什么好处?
  • 使用这个小代码可能没有必要。 Lesson 对象可以有更多的东西,而不仅仅是问题。像课程标题,一些关于文学的信息等。这可能会使代码更清晰。见en.wikipedia.org/wiki/Object-oriented_programming
猜你喜欢
  • 2022-01-15
  • 2019-07-25
  • 2020-01-10
  • 1970-01-01
  • 2012-02-22
  • 1970-01-01
  • 2013-11-19
相关资源
最近更新 更多