enter_exit.md 1.9 KB
Newer Older
F
feilong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
# Python with-as 语句(2)

实现一个范围耗时统计类。 实现了 `__enter__``__exit__` 成员的类,可以通过 with as 语法使用,程序进入和离开范围的时候会自动调用 `__enter__``__exit__` 方法。

```python
import time

class TimeSpan:
    # TODO(You): 请正确实现计时器的__enter__和__exit成员

if __name__ == '__main__':
    with TimeSpan() as t:
        for i in range(0, 1000):
            print(i)
```

下列哪个实现是**错误的**

## template

```python
import time


class TimeSpan:
    def __init__(self) -> None:
        self.start = None

    def __enter__(self):
        self.end = None
        self.start = time.time()

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.end = time.time()
        print('耗时:{}毫秒'.format((self.end-self.start)))

if __name__ == '__main__':
    with TimeSpan() as t:
        for i in range(0, 1000):
            print(i)
```

## 答案

```python
class TimeSpan:
    def __enter__(self):
        return time.time()

    def __exit__(self, exc_type, exc_val, exc_tb):
        end = time.time()
        print('耗时:{}毫秒'.format((end-exc_val)))
```

## 选项

### A

```python
class TimeSpan:
    def __enter__(self):
        self.start = time.time()

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.end = time.time()
        print('耗时:{}毫秒'.format((self.end-self.start)))
```

### B

```python
class TimeSpan:
    def __enter__(self):
        self.end = None
        self.start = time.time()

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.end = time.time()
        print('耗时:{}毫秒'.format((self.end-self.start)))
```

### C

```python
class TimeSpan:
    def __enter__(self):
        self.end = None
        self.start = time.time()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.end = time.time()
        print('耗时:{}毫秒'.format((self.end-self.start)))
```