質問

Pythonにクラスを作成しているため、SetAttr()を使用して追加されたクラスが追加されています。

class T( object ):
    def __init__( self ):
        cDict = {}
        cDict['__doc__'] = 'Inner class doc string'
        setattr( self, 'C', type('C', (), cDict ) )
.

しかし、呼び出しヘルプ(t)はそれとC. Aの構築、そしてその中のCについての情報を含み、その中のCについての情報を含み、うまく機能する。

これを行う伝統的な方法は元気です:

class T2( object ): 
    class C2( object ):
        __doc__ = 'Inner class doc string'
.

呼び出しヘルプ(T2)C2に関する情報を表示します。

誰かがここで何が起こっているのか上にいくつかの光を刈ることができますか?ありがとう。

役に立ちましたか?

解決

The two snippets you showed are not equivalent.

This:

class T( object ):
    def __init__( self ):
        cDict = {}
        cDict['__doc__'] = 'Inner class doc string'
        setattr( self, 'C', type('C', (), cDict ) )

will set a C attribute on each T instance:

>>> T.C
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'T' has no attribute 'C'
>>> t = T()
>>> t.C
<class '__main__.C'>

This is because you placed the setattr inside __init__.

While this:

class T2( object ): 
    class C2( object ):
        __doc__ = 'Inner class doc string'

will add an attribute on T2 itself:

>>> T2.C2
<class '__main__.C2'>

他のヒント

help operates on classes and types, rather than objects. However, your T only has the member C in objects (when __init__ has been run). So help can't detect it.

Your T2 also contains C2 in the class itself, so help detects it and displays the correct information.

The first way causes C to be an instance attribute of each T object.

The second way causes C to be a class attribute of the T class.

help(T) provides help on the T class (well, the object that the name T refers to, which in this case is a class). It can't know anything about any given instance of T, even if it's true for every instance (and it might not be, anyway; later code could do my_T = T(); del my_T.C).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top