在python的自定义类中实现对'with object()as f'的使用 [英] Implementing use of 'with object() as f' in custom class in python
问题描述
我必须在python中打开一个类似文件的对象(它是通过/dev/的串行连接),然后将其关闭.这是在我的课堂上的几种方法中完成的.我的工作方式是在构造函数中打开文件,然后在析构函数中关闭文件.虽然我遇到了奇怪的错误,但我认为这与垃圾收集器有关,因此,我仍然不习惯于不确切知道何时删除对象= \
I have to open a file-like object in python (it's a serial connection through /dev/) and then close it. This is done several times in several methods of my class. How I WAS doing it was opening the file in the constructor, and then closing it in the destructor. I'm getting weird errors though and I think it has to do with the garbage collector and such, I'm still not used to not knowing exactly when my objects are being deleted =\
之所以这样做,是因为每次打开它时,我必须使用tcsetattr
和一堆参数,这在整个地方都变得很烦人.所以我想实现一个内部类来处理所有事情,以便我可以使用它做
with Meter('/dev/ttyS2') as m:
The reason I was doing this is because I have to use tcsetattr
with a bunch of parameters each time I open it and it gets annoying doing all that all over the place. So I want to implement an inner class to handle all that so I can use it doing
with Meter('/dev/ttyS2') as m:
我当时在网上寻找,并且找不到关于如何实现with
语法的很好的答案.我看到它使用了__enter__(self)
和__exit(self)__
方法.但是,我要做的就是实现那些方法,并且可以使用with语法吗?还是还有更多?
I was looking online and I couldn't find a really good answer on how the with
syntax is implemented. I saw that it uses the __enter__(self)
and __exit(self)__
methods. But is all I have to do implement those methods and I can use the with syntax? Or is there more to it?
是否已经有一个有关如何执行此操作的示例,或者是否有一些关于如何在文件对象上实现的文档?
Is there either an example on how to do this or some documentation on how it's implemented on file objects already that I can look at?
推荐答案
这些方法几乎是使对象与with
语句一起使用所需的全部方法.
Those methods are pretty much all you need for making the object work with with
statement.
在__enter__
中,您必须在打开并设置文件对象后将其返回.
In __enter__
you have to return the file object after opening it and setting it up.
在__exit__
中,您必须关闭文件对象.写入它的代码将在with
语句主体中.
In __exit__
you have to close the file object. The code for writing to it will be in the with
statement body.
class Meter():
def __init__(self, dev):
self.dev = dev
def __enter__(self):
#ttysetattr etc goes here before opening and returning the file object
self.fd = open(self.dev, MODE)
return self.fd
def __exit__(self, type, value, traceback):
#Exception handling here
close(self.fd)
meter = Meter('dev/tty0')
with meter as m:
#here you work with the file object.
m.read()
这篇关于在python的自定义类中实现对'with object()as f'的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!