在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
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.fd.read()
这篇关于在python的自定义类中实现'with object() as f'的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!