<p>我认为您的第一次尝试实际上是正确的,它只需要您实现所有抽象方法(如错误所示)。你不必把实际的逻辑放在那里。下面的类将完成此任务:</p>
<pre class="lang-py prettyprint-override"><code>import io
from types import TracebackType
from typing import Optional, Type, Iterator, AnyStr, Iterable, TextIO
import sys
import typing
class MyIO(typing.TextIO):
def __enter__(self) -> TextIO:
pass
def close(self) -> None:
pass
def fileno(self) -> int:
pass
def flush(self) -> None:
pass
def isatty(self) -> bool:
pass
def read(self, n: int = ...) -> AnyStr:
pass
def readable(self) -> bool:
pass
def readline(self, limit: int = ...) -> AnyStr:
pass
def readlines(self, hint: int = ...) -> typing.List[AnyStr]:
pass
def seek(self, offset: int, whence: int = ...) -> int:
pass
def seekable(self) -> bool:
pass
def tell(self) -> int:
pass
def truncate(self, size: Optional[int] = ...) -> int:
pass
def writable(self) -> bool:
pass
def writelines(self, lines: Iterable[AnyStr]) -> None:
pass
def __next__(self) -> AnyStr:
pass
def __iter__(self) -> Iterator[AnyStr]:
pass
def __exit__(self, t: Optional[Type[BaseException]], value: Optional[BaseException],
traceback: Optional[TracebackType]) -> Optional[bool]:
pass
def write(self, text: str):
pass
def hello(f: typing.TextIO):
f.write('hello')
hello(sys.stdout) # type checks
hello(open('temp.txt', 'w')) # type checks
hello(MyIO()) # does not type check
</code></pre>