|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
class FileObject:
def __init__(self, filename='sample.txt'):
self.new_file = open(filename, 'r+')
def __del__(self):
self.new_file.close()
del self.new_file
f=FileObject('re.txt')
for i in f:
print(i)
Traceback (most recent call last):
File "C:/Users/liu/PycharmProjects/pythonProject1/venv/Scripts/41zuoye0.py", line 12, in <module>
for i in f:
TypeError: 'FileObject' object is not iterable
这个类该怎么用啊,定义实例对象f后不知道该怎么用了
你要实际指明需要进行调用的对象,比如此时的 new_file 是被文件对象赋值的变量名,若你需要读取这个对象,就应该通过 类名.实例变量 这样调用
还有就是 __del__ 魔法方法是当你对类对象调用 del 时候才会自动调用 __del__ 魔法方法
参考代码:
- class FileObject:
- def __init__(self, filename='sample.txt'):
- self.new_file = open(filename, 'r+')
- def __del__(self):
- self.new_file.close()
- del self.new_file
- f=FileObject('re.txt')
- # 读取实例属性 new_file
- data = f.new_file.read()
- for i in data:
- print(i)
-
- # 自动调用 __del__ 魔法方法,删除文件对象
- del f
复制代码
|
|