[Python] How Do I Open A File in a Subclass of BufferedIOBase in Python

Discussão em 'Python' iniciado por Stack, Agosto 12, 2025.

  1. Stack

    Stack Membro Participativo

    I want to create my own reader class that is derived from BufferedIOBase. I'd like to have multiple 'open' class methods with differing parameters to create class instances, like this:

    from __future__ import annotations

    import io

    class MyReader(io.BufferedIOBase):

    @classmethod
    def open1(cls, filename:str) -> MyReader:
    r = MyReader()
    # How do I open 'r'?
    return r

    @classmethod
    def open2(cls, buffer:bytes) -> MyReader:
    ...

    def __init__(self):
    super().__init__()

    with MyReader.open("filename") as reader:
    reader.read()


    How do I actually open the file in my class? The can't use "r = open(...)" in place of "r = MyReader()" because that won't create a "MyReader" object; and there's no available method in the MyReader class and its superclasses to do an open.

    Continue reading...

Compartilhe esta Página