簡體   English   中英

如何使python幫助系統在動態創建的模塊中顯示動態創建的類?

[英]How do I make the python help system show dynamically created classes in my dynamically created module?

我正在動態創建一個python模塊,並在該模塊中動態創建了類。 但是,在python中使用幫助功能時,這些類不會出現。 這是問題的一個例子。

import imp
Foo = imp.new_module("Foo")
Foo.Bar = type('Bar', (object,), dict(x=10, y=20))
help(Foo)

顯示以下內容。

Help on module Foo:

NAME
    Foo

FILE
    (built-in)

我希望Bar出現在CLASSES部分中。 我怎么做?

請注意, help(Foo.Bar) in module __main__描述了該類。 這是一個線索嗎?

Help on class Bar in module __main__:

class Bar(__builtin__.object)
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  x = 10
 |  
 |  y = 20

設置Bar__module__

Foo.Bar.__module__ = Foo.__name__

它會出現。 根據.__module__屬性, help()過濾掉屬於模塊的所有內容。 其余假定為外部進口。

如果將Foo.__all__設置為包括'Bar' ,則Bar將列在CLASSES部分中:

import imp
Foo = imp.new_module('Foo')
Foo.Bar = type('Bar', (object,), dict(x=10, y=20))
Foo.__all__ = ['Bar']
help(Foo)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM