如何在类中调用函数?

埃尔杜阿尔多

我尝试从文本文件中读取文本,但是当我运行代码时,它只是跳过所有命令而没有任何反应。

class mainClass:

    def __init__(self):
        filePath = input("Enter the filePath: ")
        text = mainClass.read(filePath)

    def read(self, filePath):
        text = open(filePath, mode="w+")
        string = ""
        for char in text:
            string += char
        print(string)
        return string
        f.close()`
迈克尔·加洛

您以错误的模式打开文件。“w+”代表写(和追加)。如果你正在阅读,你想使用“r”

f.close() 也什么都不做。return 语句之后的代码不会运行,并且文件名是文本,而不是 f。读取函数(用最少的代码重构)应该是这样的

    def read(self, filePath):
        text = open(filePath, mode="r")
        string = ""
        for char in text:
            string += char
        print(string)
        text.close()
        return string

init 函数中的第二行应该是 self.read,而不是 Mainclass.read。

def __init__(self):
    filePath = input("Enter the filePath: ")
    text = self.read(filePath)

此外,您只定义了一个类,这与创建类的成员不同。你会希望整个文件像这样阅读

class mainClass:

def __init__(self):
    filePath = input("Enter the filePath: ")
    text = self.read(filePath)

def read(self, filePath):
    text = open(filePath, mode="r")
    string = ""
    for char in text:
        string += char
    print(string)
    text.close()
    return string

test_class = mainClass()

此外,虽然此代码将运行,但我建议使用不同的方法来打开和关闭文件。如果使用“with”,则不必手动关闭文件

class mainClass:

def __init__(self):
    filePath = input("Enter the filePath: ")
    text = self.read(filePath)

def read(self, filePath):
    with open(filePath, mode="r") as text:
        string = ""
        for char in text:
            string += char
        print(string)
    return string

test_class = mainClass()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章