Browse Source

Withable

pull/27/head
Jure Šorn 6 years ago
parent
commit
8730e9225d
1 changed files with 22 additions and 0 deletions
  1. 22
      README.md

22
README.md

@ -758,6 +758,28 @@ class Counter:
return self.a return self.a
``` ```
### Withable
```python
class FileReader():
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.file = open(self.filename)
return self.file.read()
def __exit__(self, *args):
self.file.close()
print(f'FileReader closed {self.filename!r}')
```
```python
>>> with open('test.txt', 'w') as file:
... file.write('Hello World!')
>>> with FileReader('test.txt') as text:
... print(text)
Hello World!
FileReader closed 'test.txt'
```
### Copy ### Copy
```python ```python
from copy import copy, deepcopy from copy import copy, deepcopy

Loading…
Cancel
Save