python - 无法在 Python 中调用我的类

标签 python class call

我正在用 Python 编写一个类来修改文本文件中的一行。代码经测试在单独运行时运行良好。

class fileeditor:
    def __init__ (self,a,b):
        self.a = a
        self.b = b
        self.c = 0
        print 0
    def editinputfile (self):
        return 0
        with open (self.a,"r") as my_file:
           for line in my_file:
              if line.strip():
                  self.c+=1
        self.c=self.c-2
        with open (self.a,"r") as my_file:
            lines=my_file.readlines()
            lines[self.c]= self.b
        with open (self.a,"w") as my_file:
            my_file.write(''.join(lines))
        my_file.close()

但是当我试图从另一个文件调用它时,它不起作用。 self.a 是文本文件的地址,而 self.b 是将覆盖文本文件中一行的字符串。

from editor import fileeditor
a=".\test.txt"
b='1 2 4 5\n'
fileeditor(a, b)

最佳答案

根据您给出的示例,您似乎只是在创建新实例,而不是调用 editinputfile 方法。尝试做:

fe = fileeditor(a, b)
fe.editinputfile()

关于python - 无法在 Python 中调用我的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21342582/

相关文章:

python - 如何判断最后一个函数是否在类: Python中被调用

java - 如何从私有(private)方法调用数组?

python - 如何打印出 JSON 输出的确切字段/字符串?

python - 类型对象 'x' 没有属性过滤器

python - 预期的 LP_c_float 实例而不是列表

Java - 在 JVM 启动时加载附加类

c++ - 是否可以在 .cpp 文件而不是其头文件中定义类的静态成员函数?

python - Django 进度条

python - 如何使用 __str__ 更改对象属性的显示方式?

android - 如何从另一个 Android 应用程序通过 Skype 视频调用用户?