当前位置: 动力学知识库 > 问答 > 编程问答 >

Equivalent of struct members in Python (mainly for documentation and reading code)

问题描述:

It would be helpful to document the (private -> _x) data members of

a class in the same way I can say:

struct foo {

foo* p_a /* Documentation */

foo ** pp_b /* Documentation */

};

But for Python (arguably we are in a different programming

model here) what is the preferred way of doing it? Implicitly

defining them by references is not going to cut it when I want

to see immediately what this class models.

This would also be useful for direct conversion to UML

diagrams etc..

网友答案:

You're right, Python is a different programming model. The thing to understand is, in Python, when you see this:

class Foo(object):
    ...

It's not really a "class declaration." It's more of a "class creation." At the instant that the interpreter reaches the class.. line, and not before, a class object is created and made ready. And one thing about this class object is that is basically knows nothing about its instances.

The only time that the class has access to the instances (and data members are usually on the instances) is when it's actually running through a method. This syntax:

def bar(self, x):
    ...

is interesting. The explicit first argument is kind of a hint that something different is going on. That's right: when you write instance.bar(x), what's really happening is Foo.bar(instance, x).

Meaning that Foo's only chance at getting at the instance is with methods.

So if you want an explicit class model, your best bet may be to list it out - explicitly - in the __init__ method.

class Foo(object):
    def __init__(self):
        self._bar = None  # Bar is an important "private" member
        self._baz = None  # As is baz
        self._fizzbuzz = 4  # Of course, you can also provide defaults here

If I'm way off base here, I'd like to be corrected - but this is how I understand Python currently.

网友答案:

You can use a docstring (triple-quoted string) as the first statement in a class or method; the closest thing to a standard format for docstrings is specified as PEP 257.

class foo( object ):
    """
    This is a foo.
    _a is foo's a; there are many like it but this one is foo's.
    _b is foo's b and demons may fly out of your nose if you modify it.
    """

    def __init__( self ): ...
分享给朋友:
您可能感兴趣的文章:
随机阅读: