Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

properties - What is the right way to put a docstring on Python property?

Should I make several docstrings, or just one (and where should I put it)?

@property
def x(self):
     return 0
@x.setter
def x(self, values):
     pass

I see that property() accepts a doc argument.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Write the docstring on the getter, because 1) that's what help(MyClass) shows, and 2) it's also how it's done in the Python docs -- see the x.setter example.

Regarding 1):

class C(object):
    @property
    def x(self):
        """Get x"""
        return getattr(self, '_x', 42)

    @x.setter
    def x(self, value):
        """Set x"""
        self._x = value

And then:

>>> c = C()
>>> help(c)
Help on C in module __main__ object:

class C(__builtin__.object)
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables (if defined)
 |
 |  __weakref__
 |      list of weak references to the object (if defined)
 |
 |  x
 |      Get x

>>>

Note that the setter's docstring "Set x" is ignored.

So you should write the docstring for the entire property (getter and setter) on the getter function for it to be visible. An example of a good property docstring might be:

class Serial(object):
    @property
    def baudrate(self):
        """Get or set the current baudrate. Setting the baudrate to a new value
        will reconfigure the serial port automatically.
        """
        return self._baudrate

    @baudrate.setter
    def baudrate(self, value):
        if self._baudrate != value:
            self._baudrate = value
            self._reconfigure_port()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...