【问题标题】:Learn Python the Hard Way - Exercise 24艰难地学习 Python - 练习 24
【发布时间】:2015-05-11 10:03:00
【问题描述】:

this exercise的额外学分问题:

问:为什么你把变量叫做jelly_beans,而把名字叫做beans 稍后?

答:这是函数工作原理的一部分。请记住,在 函数变量是临时的。当你返回它时,它可以是 分配给一个变量供以后使用。我只是在制作一个名为的新变量 beans 保存返回值。

“函数内部的变量是临时的”是什么意思?这是否意味着变量在return 之后无效?好像函数缩进后,我无法打印函数部分使用的变量。

从答案中它说“当你返回它时,它可以分配给一个变量供以后使用”。有人能解释一下这句话吗?

print "Let's practice everything."
print 'You\'d need to know \'bout escape with \\ that do \n newlines and \t tabs.' 


poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""

print "-------------"
print poem
print "-------------" 


five = 10 - 2 + 3 - 6 
print "This should be five: %s" % five 

def secret_formula(started):
    jelly_beans = started * 500 
    jars = jelly_beans / 1000 
    crates = jars / 100 
    return jelly_beans, jars, crates 


start_point = 10000 
beans, jars, crates = secret_formula(start_point) 

print "With a starting point of : %d" % start_point 
print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates) 

start_point = start_point / 10 

print "We can also do that this way:" 
print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point)

【问题讨论】:

    标签: python function python-2.7


    【解决方案1】:

    这是否意味着return之后的变量无效?

    是的;当函数结束时,所有本地范围的名称(jelly_beans,在您的示例中)不复存在。名称jelly_beans 只能在secret_formula 内访问。

    好像函数缩进后,我无法打印函数部分使用的变量。

    您无法从函数外部访问它们,即使通过函数名称也是如此(因此 jelly_beanssecret_formula.jelly_beans 都不允许您访问该值)。这实际上是一件好事,因为这意味着您可以封装函数内的内部逻辑,而不会将其暴露给程序的其余部分。

    从答案中说“当你返回它时,它可以分配给一个变量供以后使用”

    只删除函数内部的本地名称,不一定是它们引用的对象。当您 return jelly_beans, jars, crates 时,这会将 objects(而不是 names)传递回名为 secret_formula 的任何东西。您可以在函数之外为对象指定相同的名称或完全不同的名称:

    foo, bar, baz = secret_formula(...)
    

    This article 是对 Python 中命名工作原理的有用介绍。

    【讨论】:

      【解决方案2】:

      由于 Python 的作用域规则,名称 jelly_beans 仅在 secret_formula 函数内有效。这就是你不能通过像print jelly_beans 在函数之外这样的语句来引用它的原因。

      请注意,secret_formula 会向其调用者返回一个元组。因此,当您键入时:

      beans, jars, crates = secret_formula(start_point) 
      

      您指定对secret_formula 的调用(带有特定参数),并将元组的内容分配给三个不同的名称。

      • jelly_beans的返回值赋值给beans
      • jars的返回值赋值给jars
      • crates的返回值赋值给crates

      在后两种情况下,重要的是要注意,即使名称相同,底层对象也可能不同(但不是由于范围规则 - 请参阅 cmets)。

      【讨论】:

      • “即使名称相同,底层对象也可能不同” - 我不确定你的意思。 Python 函数将对象的引用传回给调用者,因此它们将是完全相同的对象。
      • 我认为当赋值的 lhs 是对象属性时,覆盖的 __setitem__ 可能会完全执行其他操作,例如将新构造的对象的名称分配给 lhs。
      • 这是真的,但不是你写的,在这种情况下不适用。
      • 没错,它与这个特定问题无关 - 已澄清。
      猜你喜欢
      • 2015-05-01
      • 2013-04-06
      • 2011-12-04
      • 2016-06-28
      • 1970-01-01
      • 1970-01-01
      • 2014-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多