我定义了一个处理文件的类,但在尝试实例化该类并传递文件名时得到以下错误。让我知道问题出在哪里?
>>> 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)发布于 2011-11-17 06:20:32
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')发布于 2011-11-17 06:19:34
x = fileprocess应为x = fileprocess()
当前x引用的是类本身,而不是类的实例。因此,当您调用x.pread('c:/test.txt')时,这与调用fileprocess.pread('c:/test.txt')是相同的
发布于 2011-11-17 09:19:33
但是为什么要使用写模式来读函数呢?也许是pwrite?
https://stackoverflow.com/questions/8159525
复制相似问题