2011-11-16 27 views
1

我已经定义了一个类来处理文件,但在尝试实例化类并传递文件名时出现以下错误。 让我知道会是什么问题?Python上的基本类

>>> 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) 

回答

7

x = fileprocess并不意味着xfileprocess的实例。这意味着x现在是fileprocess类的别名。

您需要使用()创建一个实例。

x = fileprocess() 
x.pread('c:/test.txt') 

此外,根据您的原代码,你可以使用x创建类的实例。

x = fileprocess 
f = x() # creates a fileprocess 
f.pread('c:/test.txt') 
3

x = fileprocess应该x = fileprocess()

目前x指的是类本身,而不是类的实例。因此,当您拨打电话x.pread('c:/test.txt')与拨打电话fileprocess.pread('c:/test.txt')

0

但为什么读功能使用写模式?也许它是pwrite?