Python基本类

2024-10-06 12:33:22 发布

您现在位置: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)

Tags: 文件实例testselftxt定义文件名def
3条回答

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

x = fileprocess应该是x = fileprocess()

当前x引用的是类本身,而不是类的实例。所以当你调用x.pread('c:/test.txt')时,这和调用fileprocess.pread('c:/test.txt')是一样的

但为什么要用写模式来读函数呢?也许是pwrite?你知道吗

相关问题 更多 >