简体   繁体   English

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

[英]Importing class then passing argument to function

I have a python file: 我有一个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")

I have to write the Ford class, which has a fordit function, which opens the file passed as the argument. 我必须编写Ford类,它具有一个fordit函数,该函数可以打开作为参数传递的文件。 I wrote this: 我这样写:

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

But I get the error "TypeError: fordit() takes exactly 1 argument (2 given)". 但是我收到错误消息“ TypeError:fordit()恰好接受1个参数(给定2个)”。 What is the problem? 问题是什么?

You didn't define fordit with the necessary arguments. 您没有使用必要的参数定义fordit f.fordit(x) is equivalent to Ford.fordit(f, x) , so you need to define it to take two arguments, the first being the object calling the method and conventionally (but not necessarily) named self . f.fordit(x)等同于Ford.fordit(f, x) ,因此您需要定义它以接受两个参数,第一个是调用该方法的对象,并且按惯例(但不一定)命名为self

(Unrelated, but you should use a with statement, which ensures that the file is closed even if an error occurs while it is open. The file is closed implicitly once the with statement completes.) (无关,但你应该使用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