Skip to main content
 首页 » 编程设计

Python 类基础

2025年05月04日16wuhuacong

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

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

请您参考如下方法:

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