python继承自两个类_继承自python的'File'类并定义自定义行为 - python2和3-问答-阿里云开发者社区-阿里云...

我试图自定义文件句柄的行为在两个python 2.7和python 3.x(至少>=3.6)的库中。

我正在实现的自定义行为要求在close调用方法时执行某些操作(direct(fh.close())或作为__exit__()方法的结果)。

我还试图添加一个额外的方法 - 让我们调用它custom_copy()。

我理想是的是给我的用户一个他们可以正常使用的文件句柄(读/读/写/ ...),但在幕后也有一些特殊的逻辑。

这是我目前正在使用的...

from os import fsync

def custom_open(filepath, mode='rt', args*kwargs):

# Open the file normally using open_args

orig_file_handle = open(filepath, mode, *args, **kwargs) # pylint: disable=star-args

# Preserve original close function

original_close_fn = orig_file_handle.close

# Create a custom close function

def custom_close_fn(*args, **kwargs):

original_close_fn(*args, **kwargs)

print("Do Something Custom")

orig_file_handle.close = custom_close_fn

# Add custom_copy function

def custom_copy_fn(*args, **kwargs):

if orig_file_handle.closed:

raise ValueError("I/O operation on closed file")

# Ensure buffer has been flushed before rsync

orig_file_handle.flush()

fsync()

return _my_custom_copy(filepath, *args, **kwargs)

orig_file_handle.custom_copy = custom_copy_fn

return orig_file_handle

上面的代码可以使用python3.7.0,但是python2.7.8它失败了

orig_file_handle.close = custom_close_fn

E AttributeError: 'file' object attribute 'close' is read-only

我还尝试了另一种涉及SubClassing的方法type(orig_file_handle),但是还有其他一些问题......

def custom_open(filepath, mode='rt', open_args=None):

open_args = open_args or {}

open_args['mode'] = mode

# Open the file normally using open_args

orig_file_handle = open(filepath, **open_args) # pylint: disable=star-args

class CustomFile(type(orig_file_handle)):

def __init__(self, file_handle):

# pylint: disable=super-init-not-called

self.__dict__ = file_handle.__dict__.copy()

def close(self, *args, **kwargs):

# Execute normal file handle close

super(CustomFile, self).close(*args, **kwargs)

print("Do Something Custom")

def custom_copy(self, *args, **kwargs):

if self.closed: # pylint: disable=no-member

raise ValueError("I/O operation on closed file")

self.flush() # pylint: disable=no-member

fsync()

return _my_custom_copy(filepath, *args, **kwargs)

return CustomFile(orig_file_handle)

在python2.7.8这失败了

self.__dict__ = file_handle.__dict__.copy()

E AttributeError: 'file' object has no attribute '__dict__'

而在python3.7.0它失败了

self.__dict__ = file_handle.__dict__.copy()

E AttributeError: attribute '__dict__' of '_io._IOBase' objects is not writable

任何想法如何解决这个问题,还是有其他模式我应该遵循以获得我想要的结果?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值