【问题标题】:Magic method __str__ is not called on str call魔术方法 __str__ 不调用 str 调用
【发布时间】:2018-11-06 13:05:38
【问题描述】:

我是module-wrapper 库的创建者,也是aioify 库的作者之一。问题出现在 module-wrapper 库中封装的魔术方法中(我从 aioify.aioify 调用 module_wrapper.wrap,但这没关系)。

我有以下代码:

#!/usr/bin/env python
from aioify import aioify


async def main():
    from pathlib import Path
    # noinspection PyPep8Naming
    AioPath = aioify(obj=Path)
    return await AioPath.create('/tmp')


if __name__ == '__main__':
    import asyncio
    loop = asyncio.get_event_loop()
    path = loop.run_until_complete(main())
    path_str = str(path)
    print(path_str)

我希望得到以下输出:

/tmp

但我明白了:

<module_wrapper.wrap.<locals>.ObjectProxy object at 0x7f64266a9b00>

我不明白为什么。当我打电话时:

path_str = path.__str__()
print(path_str)

我得到了我的期望:

/tmp

当我设置断点inside魔术方法包装函数调试器不会停止。

UPD0: 要重现这一点,您需要安装 module-wrapperaioify(来自 tarball,因为它没有在 PyPI 上发布)。不要忘记之前创建virtualenv!):

pip install module-wrapper==0.1.26
pip install https://github.com/yifeikong/aioify/archive/0.3.0.zip

【问题讨论】:

  • 请使用minimal reproducible example 更新您的问题。我们无法提供在您得到答复后立即更改的代码链接...
  • 请注意,魔术方法可能不遵循正常的属性查找(参考special method lookup)。 __str__ 真的定义在类(而不是实例)上吗?
  • @Aran-Fey,谢谢!我更新了问题。

标签: python python-3.x wrapper magic-methods


【解决方案1】:

终于解决了。 mseifert 是对的,问题是我没有包装类的魔法方法。请参阅 GitHub 和 PyPI 上的固定版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 2014-05-21
    相关资源
    最近更新 更多