Вопрос

Я создаю класс в Python, который затем добавляют некоторые вложенные классы, добавленные с помощью SetAttr ().

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

Тем не менее, Shaling Help (T) не включает в себя и информацию о C. Создание T, а затем A 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