Python 来自另一个类实例的子类
我正在尝试向临时文件添加功能(新方法)。 通常,该文件由Python 来自另一个类实例的子类,python,python-3.x,Python,Python 3.x,我正在尝试向临时文件添加功能(新方法)。 通常,该文件由tempfile.NamedTemporaryFile(*args,**kwargs)调用,但“NamedTemporaryFile”是一个函数,而不是一个类。 我不想跳过这个函数。我想让函数创建文件,但也添加我的方法 我尝试了以下方法(以及其他方法),但我的方法没有被认可: import tempfile from tempfile import _TemporaryFileWrapper class TempFile(_Temporar
tempfile.NamedTemporaryFile(*args,**kwargs)
调用,但“NamedTemporaryFile”是一个函数,而不是一个类。
我不想跳过这个函数。我想让函数创建文件,但也添加我的方法
我尝试了以下方法(以及其他方法),但我的方法没有被认可:
import tempfile
from tempfile import _TemporaryFileWrapper
class TempFile(_TemporaryFileWrapper):
def __new__(cls, *args, **kwargs):
ret= tempfile.NamedTemporaryFile(args, kwargs)
self = cls.__init__(ret)
return self
def __init__(self, mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None):
print('__init__')
def MyMethod(self):
print('my method works')
有什么想法吗?好的,这似乎很管用,只是感觉不太对劲。 如果有人有更好的想法,我会欣然接受他们的回答
import tempfile
class TempFile(object):
def __init__(self, mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None):
t = tempfile.NamedTemporaryFile(mode)
self.file = t
# These are actually not necessary, but they make it it easier with auto-complete in the IDE.
self.name= t.name
self.close = t.close
self.write = t.write
def __get__(self):
return self.file
def MyMethod(self):
print('my method works')
if __name__ == '__main__':
t = TempFile(mode='w')
t2 = tempfile.NamedTemporaryFile(mode='w')
print(t.name)
print(t2.name)
t.MyMethod()
您可以子类化
tempfile.\u TemporaryFileWrapper
,然后对名称进行monkey修补,以便NamedTemporaryFile
返回子类的实例
class TempFile(tempfile._TemporaryFileWrapper):
...
tempfile._TemporaryFileWrapper = TempFile
x = NamedTemporaryFile(...)
这应该是可行的(未经测试),因为
NamedTemporaryFile
是硬编码的,以返回\u TemporaryFileWrapper
的实例,无论该名称绑定到什么地方。删除所有未使用的参数后,有什么感觉不对劲?通常,get应该返回self。让它返回其他东西看起来像是“作弊”,感觉这种方法会有意外的后果,但我不确定定义\uu get\uu
的目的是什么?您的测试代码在没有它的情况下工作相同。除此之外,看起来您刚刚发现了。使用get,TempFile(mode='w')返回file对象,因此我可以使用t2执行,例如,t.write('text')。我看不出装饰程序与此有什么关系。如果我理解正确,您可以在TempFile和TempFile之间创建循环引用。\u TemporaryFileWrapperNo,因为我只是重新绑定名称TempFile
子类化任何类TempFile.\u TemporaryFileWrapper
用于引用。