创建一个继承 TextIOWrapper 的自定义类

问题描述

我正在尝试在一个类中创建一个方法,该方法返回一个行为类似于缓冲文件流的对象(python 的内置类,TextIOWrapper), 另外,我正在尝试为其添加更多功能方法)。

它看起来类似于:

class ReadFile:

    def __init__(self):
        self._i = 0

    def do_magic(self,file):
        # ...

        io = open(file)
        return io



if __name__ == "__main__":
    import pandas as pd

    rf = ReadFile()
    a = rf.do_magic("./data.csv")
    data = pd.read_csv(a) # this should work

    # a.desired_feature() # I want this as well

我的第一次尝试是创建 TextIOWrapper 的子类并进行转换。


class _TextIOWrapper(io.TextIOWrapper):
    pass

# ...

    def do_magic(self,file):
        # ...

        io = open(file)

        io.__class__ = _TextIOWrapper
        return io

它给了我一个TypeError

Traceback (most recent call last):
  File "d.py",line 56,in <module>
    a = rf.do_magic("./data.csv")
  File "d.py",line 45,in do_magic
    io.__class__ = _TextIOWrapper
TypeError: __class__ assignment only supported for heap types or ModuleType subclasses

我的第二次尝试是在内置函数添加功能方法)。

def add_method(cls):
    def decorator(func):
        @wraps(func)
        def wrapper(self,*args,**kwargs):
            return func(*args,**kwargs)
        setattr(cls,func.__name__,wrapper)
        return func
    return decorator


@add_method(io.TextIOWrapper)
def desired_feature(self):
        return None

这给了我另一个TypeError

Traceback (most recent call last):
  File "d.py",line 26,in <module>
    @add_method(io.TextIOWrapper)
  File "d.py",line 21,in decorator
    setattr(cls,wrapper)
TypeError: can't set attributes of built-in/extension type '_io.TextIOWrapper'

是否还有其他解决方法可以使 desired_feature() 正常工作?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...