python - python独立函数返回调用它的对象实例
问题描述
我有一个非常奇怪的问题。
我需要返回一个类对象来调用一个应该返回调用它的类对象的函数。我知道我知道。把它想象成一个人为的练习,虽然对我来说这是一个非常真实的需要。
def baz():
# return the object instance that calls me.
class Foo():
def bar(self, func):
return func() # should return the Foo object but how???
new_foo = Foo()
new_foo_instance = new_foo.bar(baz)
是否可以写任何东西baz()
来返回调用它的对象?
编辑:
回答评论:
我尝试使用检查,但没有成功,我什至查看了整个堆栈,但找不到与new_foo
对象匹配的条目:
new_foo
当我打印出来时是这样的:<__main__.Foo object at 0x0000029AAFC4C780>
当我打印出整个堆栈时,在其中找不到条目:
def baz():
print(inspect.stack())
return inspect.stack() #[1][3]
>>> [FrameInfo(frame=<frame object at 0x0000029AADB49648>, filename='return_caller.py', lineno=5, function='baz', code_context=[' print(inspect.stack())\n'], index=0), FrameInfo(frame=<frame object at 0x0000029AAD8F0DE8>, filename='return_caller.py', lineno=11, function='bar', code_context=[' return func() # should return the Foo object but how???\n'], index=0), FrameInfo(frame=<frame object at 0x0000029AAD8AC588>, filename='return_caller.py', lineno=19, function='<module>', code_context=['new_foo_instance = new_foo.bar(baz)\n'], index=0)]
所以我不是想让它返回一个新的实例Foo
,而是实际上与它完全相同的实例new_foo
。
解决方案
使用检查:
import inspect
def baz():
frame_infos = inspect.stack() # A list of FrameInfo.
frame = frame_infos[1].frame # The frame of the caller.
locs = frame.f_locals # The caller's locals dict.
return locs['self']
class Foo():
def bar(self, func):
return func()
f1 = Foo()
f2 = f1.bar(baz)
print(f1)
print(f2)
print(f2 is f1) # True
或作弊:
def baz():
return getattr(baz, 'self', None)
class Foo():
def bar(self, func):
func.self = self # Functions can be a place to store global information.
return func()
推荐阅读
- git - 如何删除根目录深处的 node_modules 一个文件夹
- javascript - Javascript在UTC TIMEZONE中从“yyyy-mm-ss”字符串中减去一天
- spring - Spring Batch:批处理的数据源和步骤的数据源
- python - 升级到 Macos Big Sur 后 Reportlab 安装失败
- python - 如何去除二值图像中的噪声?
- delphi - 我可以在 Delphi 6 / Delphi 7 中更改 TRAdioButton 上的字体字符集吗
- logging - Fluent Bit Input 插件“转发”是否支持多行日志处理?
- machine-learning - 你应该在张量流中的超参数搜索期间设置随机种子数吗?
- dc.js - 在 dc-js geoChoropleth 图表的标题中使用完整的组记录
- python - neomodel 无法匹配记录