[英]Learn Python the Hard Way, exercise 20, confused about functions
在進行練習的過程中,我偶然發現了一些東西,即使經過研究,我根本無法掌握。
這是代碼的具體位:
def print_all(f):
print f.read()
對於整個腳本: http : //learnpythonthehardway.org/book/ex20.html
真正令我困惑的是(f)部分。 那個f來自哪里? 它的目的是什么?
哦,好的,提前謝謝!
f是一個文件或一些其他對象,支持傳遞給print_all的read方法。 read方法讀取所有內容。 print語句打印出來。
f
是函數的參數,它應該是一個像object這樣的文件,並且在提供的示例中使用open調用構造。
script, input_file = argv
#...
current_file = open(input_file)
#...
#here, the body of current_file is executed,
#with f replaced by the value of current_file
print_all(current_file)
其中argv
(由sys
模塊提供)是命令行上提供的字符串列表,例如["ex20.py", "test.txt"]
f
是一個參數。 它被傳遞給函數。 例如:
def double(n):
return n * 2
給定此函數定義,調用:
x = double(2)
print(x)
會產生:
4
您也可以簡單地進行print(double(2))
。
此參數傳遞是函數,對象和對象方法的基本部分; 理解這是理解任何 Python代碼所必需的。
他們提供的例子
script, input_file = argv
$ python ex20.py test.txt
意味着f
是文件。
f
是一個參數,在您向該函數傳遞內容時定義:
script, input_file = argv
current_file = open(input_file)
print_all(current_file)
f
是print_all()
用於傳遞給它的第一個參數的名稱。
print_all(some_file)
print_all('Hello, World!')
print_all(23)
上面將運行print_all()
三次,在包含some_file
的函數中使用f
, 'Hello, World!'
,每次運行期間23
次。
你看我昨天開始學習Python了。 但讓我試着澄清一下,
script, input_file = argv
將傳遞的參數(腳本名稱和輸入文件名)放入相應的變量中。
current_file = open(input_file)
這將為您傳遞的文件名創建文件處理程序對象
print_all(current_file)
這稱為有問題的功能。 因此,您定義了一個類似def functionName(arg1, arg2)
以通知此函數將采用多少參數(以及它的名稱是什么)。
所以,你定義了def print_all(f)
說這個函數接受一個具有本地名稱f的參數,該參數將用於該函數內的進一步使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.