我已经定义了一个类来处理文件但是当我尝试实例化类并传递文件名时会出现以下错误。 让我知道会出现什么问题?
>>> class fileprocess:
... def pread(self,filename):
... print filename
... f = open(filename,'w')
... print f
>>> x = fileprocess
>>> x.pread('c:/test.txt')
Traceback (most recent call last):
File "", line 1, in
TypeError: unbound method pread() must be called with
fileprocess instance as first argument (got nothing instead)
答案 0 :(得分:7)
x = fileprocess
并不意味着x
是fileprocess
的实例。这意味着x
现在是fileprocess
类的别名。
您需要使用()
创建实例。
x = fileprocess()
x.pread('c:/test.txt')
此外,根据您的原始代码,您可以使用x
创建类实例。
x = fileprocess
f = x() # creates a fileprocess
f.pread('c:/test.txt')
答案 1 :(得分:3)
x = fileprocess
应为x = fileprocess()
目前x
指的是类本身,而不是类的实例。因此,当您致电x.pread('c:/test.txt')
时,与调用fileprocess.pread('c:/test.txt')
答案 2 :(得分:0)
但为什么要使用写模式进行读取功能?也许是pwrite?