Python模块可以有__repr__吗?

8 投票
5 回答
1947 浏览
提问于 2025-04-15 15:57

一个Python模块可以有一个__repr__吗?我的意思是想做一些像这样的事情:

import mymodule
print mymodule

编辑:我指的是一个用户自定义的repr!

5 个回答

6

模块可以有一个叫做 __repr__ 的函数,但在获取模块的表示时,这个函数不会被调用。

所以,不,你不能实现你想要的效果。

9

你可以实现这个效果——前提是你愿意走上黑暗的一面。

把这个添加到 mymodule.py:

import sys

class MyReprModule(mymodule.__class__):
  def __init__(self, other):
    for attr in dir(other):
      setattr(self, attr, getattr(other, attr))

  def __repr__(self):
    return 'ABCDEFGHIJKLMNOQ'

# THIS LINE MUST BE THE LAST LINE IN YOUR MODULE
sys.modules[__name__] = MyReprModule(sys.modules[__name__])

看看这个效果:

>>> import mymodule
>>> print mymodule
ABCDEFGHIJKLMNOQ

我隐约记得,在之前尝试类似的“邪恶”技巧时,设置像 __class__ 这样的特殊属性会遇到麻烦。不过在测试这个的时候,我没有遇到那个问题。如果你碰到这个问题,只需捕获异常,然后跳过那个属性就可以了。

12

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

但是你不能通过文档字符串找到你想要的功能吗?

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 交互式命令行的会话:

>>> 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)>"

所以我认为问题出在这些 槽包装对象上(根据链接中的内容来看),这些对象绕过了通常的“Python”查找项属性的方式。

对于这些类方法,CPython 返回指向这些对象相应方法的 C 指针(然后这些指针被包装在槽包装对象中,以便可以从 Python 端调用)。

撰写回答