【问题标题】:About scope in Python [duplicate]关于 Python 中的范围 [重复]
【发布时间】:2017-03-12 16:49:51
【问题描述】:

在此代码中,pelts 在 with 语句中定义以打开文件。命令“打印”能够访问它(Python 2.7)。像 with、for、while 这样的代码段不会像函数那样限制范围吗?

def run_funct():
''' (input_type) -> output_type

Function docstring
'''

# Put the file into a file handler
with open('hopedale.txt') as hopedale_file:

    # Read first line and move file cursor to the beginning of next line
    hopedale_file.readline()

    # We know that info lines begin on the second line, and 'startswith'
    # a `#` symbol, skip these lines after processing the first one.
    data = hopedale_file.readline().strip()
    while data.startswith('#'):
        data = hopedale_file.readline().strip()

    # When the input line no longer begins with a '#' symbol, store
    # the number of pelts on the first data line
    pelts = int(data)

    # Then process the rest of the lines with 'for ___ in'
    for data in hopedale_file:
        pelts += int(data.strip())

# Print pelts
print 'Number of pelts is:', pelts

【问题讨论】:

  • 不,他们不限制范围

标签: python


【解决方案1】:

在 python 中,only 函数和类定义了新的作用域。 if、for、while、with 等不要!

【讨论】:

  • 谢谢。出于好奇,您指出“在 python 中”,您知道它在 JavaScript 中是否相同?我目前都在学习。
  • @hikinthru Yes
【解决方案2】:

pelts 在全局范围内,因此在with 之外可用。 with 不会创建自己的作用域。

【讨论】:

    猜你喜欢
    • 2019-12-20
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多