gpt4 book ai didi

python - python 模块可以有 __repr__ 吗?

转载 作者:太空狗 更新时间:2023-10-30 00:22:37 35 4
gpt4 key购买 nike

python 模块可以有 __repr__ 吗?这个想法是做类似的事情:

import mymodule
print mymodule

编辑:精度:我的意思是用户定义 repr!

最佳答案

简答:基本上答案是否定的。

但是您不能使用文档字符串找到您正在寻找的功能吗?

testmodule.py
""" my module test does x and y
"""
class myclass(object):
...
test.py
import testmodule
print testmodule.__doc__

长答案:

您可以在模块级别定义自己的 __repr__(只需提供 def __repr__(...),但您必须这样做:

import mymodule
print mymodule.__repr__()

获得您想要的功能。

看看下面的 python shell session :

>>> import sys                 # we import the module
>>> sys.__repr__() # works as usual
"<module 'sys' (built-in)>"
>>> sys.__dict__['__repr__'] # but it's not in the modules __dict__ ?
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: '__repr__'
>>> sys.__class__.__dict__['__repr__'] # __repr__ is provided on the module type as a slot wrapper
<slot wrapper '__repr__' of 'module' objects>
>>> sys.__class__.__dict__['__repr__'](sys) # which we should feed an instance of the module type
"<module 'sys' (built-in)>"

所以我认为问题在于这些 slot wrapper objects这(从链接中可以读取的内容)的结果是绕过了通常的“python”查找项目属性的方式。

对于这些类方法,CPython 返回指向这些对象上相应方法的 C 指针(然后将其包装在插槽包装器对象中,以便从 python 端调用)。

关于python - python 模块可以有 __repr__ 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1725515/

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