Python 如何在类中调用函数?
我试图从文本文件中读取文本,但当我运行代码时,它只是跳过所有命令,什么也没发生Python 如何在类中调用函数?,python,class,Python,Class,我试图从文本文件中读取文本,但当我运行代码时,它只是跳过所有命令,什么也没发生 class mainClass: def __init__(self): filePath = input("Enter the filePath: ") text = mainClass.read(filePath) def read(self, filePath): text = open(filePath, mode=&qu
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语句后的代码不运行,文件名为text,而不是f。具有最小代码重构的read函数应该是这样的
def read(self, filePath):
text = open(filePath, mode="r")
string = ""
for char in text:
string += char
print(string)
text.close()
return string
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()
init函数中的第二行应该是self.read,而不是Mainclass.read
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
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()
此外,虽然这段代码将运行,但我建议使用不同的方法打开和关闭文件。如果与一起使用,则不必手动关闭文件
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()
你知道什么是类吗?因为这段代码看起来像是由一个不懂Python的Java程序员教的。在Python中,没有理由仅仅为了成为一个主类而拥有一个类。Python有顶级函数,它们工作得很好,不需要像Java中那样的笨拙的黑客。嗨,是的,我是一名Java程序员,现在正在尝试学习Python