簡體   English   中英

導入類,然后將參數傳遞給函數

[英]Importing class then passing argument to function

我有一個python文件:

# -*- coding: utf-8 -*-

from bead import Ford

szotar = {"The" : "A", "sun": "nap", "shining" : "süt", "wind" : "szél", "not" : "nem", "blowing" : "fúj"}

fd = Ford(szotar)
fd.fordit("teszt.txt")

我必須編寫Ford類,它具有一個fordit函數,該函數可以打開作為參數傳遞的文件。 我這樣寫:

class Ford(dict):
    def fordit(read):
        fajl = open(read)
        for sor in fajl:
            print(sor)
        fajl.close()

但是我收到錯誤消息“ TypeError:fordit()恰好接受1個參數(給定2個)”。 問題是什么?

您沒有使用必要的參數定義fordit f.fordit(x)等同於Ford.fordit(f, x) ,因此您需要定義它以接受兩個參數,第一個是調用該方法的對象,並且按慣例(但不一定)命名為self

(無關,但你應該使用with聲明,這保證了即使處於打開狀態時發生錯誤,該文件被關閉。該文件隱含地關閉,一旦with語句完成。)

class Ford(dict):
    def fordit(self, read):
        with open(read) as fajl:
            for sor in fajl:
                print(sor)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM