关于Python中的作用域
在这段代码中,毛皮是在with语句中定义的,用于打开文件。命令“print”可以通过Python 2.7访问它。代码部分是否喜欢with、for,而不是像函数那样限制范围关于Python中的作用域,python,Python,在这段代码中,毛皮是在with语句中定义的,用于打开文件。命令“print”可以通过Python 2.7访问它。代码部分是否喜欢with、for,而不是像函数那样限制范围 def run_funct(): ''' (input_type) -> output_type Function docstring ''' # Put the file into a file handler with open('hopedale.txt') as hopedale_file: # R
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中,只有函数和类定义了新的作用域。如果、为了、暂时、与……不 在python中,只有函数和类定义了新的作用域。如果、为了、暂时、与……不 毛皮在全局范围内,因此可在外部使用。with不创建自己的作用域。毛皮位于全局作用域中,因此在with外部可用。with不创建自己的范围。不,他们不限制范围不,他们不限制范围谢谢。出于好奇,您指出“在python中”,您知道它在JavaScript中是否相同吗?我目前正在学习这两种方法。@hikinthru谢谢。出于好奇,您指出“在python中”,您知道它在JavaScript中是否相同吗?我目前正在学习这两种方法。@hikinthru