python模块可以有__repr__吗?

sta*_*tti 5 python module

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

import mymodule
print mymodule
Run Code Online (Sandbox Code Playgroud)

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

Chr*_*heD 8

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

但是,您不能使用docstrings找到您正在寻找的功能吗?

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

答案很长:

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

import mymodule
print mymodule.__repr__() 
Run Code Online (Sandbox Code Playgroud)

获得您想要的功能.

看看下面的python shell会话:

>>> 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)>"
Run Code Online (Sandbox Code Playgroud)

所以我认为问题在于这些插槽包装器对象(从链接中可以读取的内容)具有绕过通常的'python'方式查找项属性的结果.

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


Lar*_*ngs 6

如果您愿意转向部队的阴暗面,可以实现此效果。

将此添加到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__])
Run Code Online (Sandbox Code Playgroud)

瞧瞧:

>>> import mymodule
>>> print mymodule
ABCDEFGHIJKLMNOQ
Run Code Online (Sandbox Code Playgroud)

我朦胧地记得,在以前尝试类似的恶意黑客的尝试中,难以设置诸如的特殊属性__class__。测试时我没有那么麻烦。如果遇到此问题,只需捕获异常并跳过该属性即可。


Ned*_*der 5

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

所以不,你不能做你想做的。