2013-04-19 3 views
0

동적으로 생성 된 클래스를 사용하여 파이썬 모듈을 동적으로 생성합니다. 그러나 파이썬에서 help 함수를 사용할 때 클래스는 나타나지 않습니다. 다음은 문제의 예입니다.어떻게 동적으로 생성 된 모듈에 동적으로 생성 된 클래스를 보여주는 파이썬 도움말 시스템을 만들 수 있습니까?

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) 

나는 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 

답변

2

설정 __module__Bar의 :

Foo.Bar.__module__ = Foo.__name__ 

하고 표시합니다. help().__module__ 속성에 따라 이 아닌 모든 모듈을 필터링하여 모듈의 일부로 필터링합니다. 나머지는 외부 수입으로 가정합니다.

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

당신이 'Bar'을 포함 Foo.__all__을 설정하면

은 다음 BarCLASSES 섹션에 나열됩니다. 대답 해줘서 고마워.
+0

이 또한 작동하지만, 나는 __module__를 설정하면 내 요구에 더 적합하다고 생각 : –

관련 문제