gpt4 book ai didi

python - 我可以将另一个类的实例方法指定为我的方法的变量吗?

转载 作者:太空宇宙 更新时间:2023-11-04 01:40:18 25 4
gpt4 key购买 nike

我对 python 还是比较陌生,单独学习了 1-2 年,并且正在尝试改进我的代码结构,所以我正在重构我编写的一些旧程序。在一个程序中,我定义了几个写入文件的方法。第一个使用“写入”来转储巨大的 http 响应。第二个使用“writelines”来转储各种派生列表,例如链接列表、表单列表或其他提取的数据。

我最初考虑了文件的命名:

    @property
def baseFilename(self):
unacceptable = re.compile(r'\W+')
fname = re.sub(unacceptable,'-',self.myUrl)
t = datetime.datetime.now()
dstring = "%s%s%s%s%s%s" % (t.year, t.month, t.day, t.hour, t.minute, t.second)
fullname = fname + '_' + dstring + '.html'
return fullname

但是我在每个写方法中都有一大段冗余代码:

    def writeFile(self, someHtml, writeMethod=write, prefix="RESPONSE_"):
'''The calling functions will supply only the data to be written and
static prefixes, e.g. "full_" for the entire http-response.
'''

fullpath = self.myDump + prefix + self.baseFilename
with open(fullpath, 'w') as h:
h.write(someHtml)
h.close()
print "saved %s" % fullpath
return fullpath

def writeList(self, someList, prefix="mechList_"):
'''Like write file but for one of the many lists outputted.
How do I refactor this, since redundant?
'''

fullpath = self.myDump + prefix + self.baseFilename
with open(fullpath, 'w') as h:
h.writelines(someList)
h.close()
print "saved %s" % fullpath
return fullpath

我希望能够为每个指定要使用的写入方法的函数添加一个变量,例如(写入方法=写入线)。我考虑过只传递一个字符串并使用其中一个黑魔法函数——我猜是 exec()——但这不可能是正确的,因为似乎从来没有人使用过这些函数。整个例子可能相对愚蠢,因为我可以绕过它,但我决定我会受益于知道如何传递这些类型的实例方法(这是正确的术语吗?)。这与绑定(bind)和解除绑定(bind)有关吗?我需要一个好的答案是传递“write”、“writelines”等所需的语法。可以简单如:writeMethod = insert_your_syntax_here。不过会喜欢额外的解释或指导。谢谢。

最佳答案

您可以从对象中获取“绑定(bind)方法”,然后无需引用对象即可将其作为函数调用。

f = obj.method
f(args)
# is equivalent to
obj.method(args)

但是,这对您没有用,因为您创建了您只想在方法中使用的对象 - 您不能将它作为绑定(bind)方法传递到那里。您可以分解出 fullpath 的创建,尽管这只会为您节省一半的冗余。一种我认为有点矫枉过正的选择是传递一个回调,该回调返回用于写入的函数。

另一种选择是装饰器,用于分解所有公共(public)部分并将其余部分推送到回调中,即装饰函数:

def uses_file(prefix_default):
def decorator(f):
@functools.wraps(f)
def decorated(self, data, prefix=prefix_default):
fullpath = obj.myDump + prefix + obj.baseFilename
with open(fullpath, 'w') as h:
f(h, data, prefix)
print "saved", % fullpath
return fullpath
return decorated
return decorator

# ...

@uses_file(default_prefix="RESPONE_")
def writeFile(self, someHtml, prefix):
'''...'''
h.write(someHtml)

@uses_file(default_prefix="mechList_")
def writeList(self, someList, prefix):
'''...'''
h.writelines(someList)

关于python - 我可以将另一个类的实例方法指定为我的方法的变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5803634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com