Python基础课程

use*_*619 1 python class

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

>>> 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)
Run Code Online (Sandbox Code Playgroud)

wkl*_*wkl 7

x = fileprocess并不意味着x是一个例子fileprocess.它意味着x现在是fileprocess该类的别名.

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

x = fileprocess()
x.pread('c:/test.txt')
Run Code Online (Sandbox Code Playgroud)

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

x = fileprocess
f = x() # creates a fileprocess
f.pread('c:/test.txt')
Run Code Online (Sandbox Code Playgroud)