导入类,然后将参数传递给函数

2024-06-28 19:35:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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个)”。有什么问题


Tags: 文件thefromimportreadutfsuncoding
1条回答
网友
1楼 · 发布于 2024-06-28 19:35:04

您没有使用必要的参数定义forditf.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)

相关问题 更多 >