加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

有没有理由把代码放在Python的docstring之前?

发布时间:2020-12-20 11:51:38 所属栏目:Python 来源:网络整理
导读:我在其他人的 Python代码中看到他们在函数的docstring之前粘贴了一些检查;这样的事情: def func(args): if x_version != 1.7: return """docstring is here""" # function body code # ... 是否有任何情况需要或者必须在docstring之前放置一些代码来解决任
我在其他人的 Python代码中看到他们在函数的docstring之前粘贴了一些检查;这样的事情:

def func(args):
  if x_version != 1.7:
    return
  """docstring is here"""
  # function body code
  # ...

是否有任何情况需要或者必须在docstring之前放置一些代码来解决任何问题?是否有任何特殊情况需要引入这种风格,或者它总是只是一个糟糕的造型,因此必须修复到这样的东西?

def func(args):
  """docstring is here"""
  if x_version != 1.7:
    return
  # function body code
  # ...

解决方法

如果它是函数体中的第一个语句,Python将只选取一个docstring.在它之前放置代码意味着字符串完全被忽略:

>>> def func(args):
...   if x_version != 1.7:
...     return
...   """docstring is here"""
...
>>> func.__doc__ is None
True

如果您希望docstring实际上有任何效果,则不应该这样做.

从Python reference documentation:

A string literal appearing as the first statement in the function body is transformed into the function’s __doc__ attribute and therefore the function’s docstring.

大胆强调我的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读