Python 类基础

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

最佳答案

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

关于Python 类基础,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8159525/

相关文章:

python - scapy - srp 没有将我的数据包发送到正确的网络接口(interface)

python - 在 Python 中附加到 gzip 文件不起作用

python - 导入错误 : No module named sysconfig--can't get pip working

c++ - c++ 类实例成员是如何在机器级别传递的?

delphi - 我什么时候应该在 Delphi 中使用增强的记录类型而不是类?

C++: friend 模板类/模板非类型参数

python - 访问 Jupyter Notebook 中的根目录

python - 打印错误和隐藏名称

JAVA 从文本文件创建事件列表

c++ - 有没有办法在 Dyalog APL 中⎕NA 导入一个 dll 导出的 C++ 类?