Python代码可读性

leg*_*esh 13 python

我有静态类型语言的编程经验.现在用Python编写代码我觉得它的可读性有些困难.让我们说我有一个班级主持人:

class Host(object):
  def __init__(self, name, network_interface):
    self.name = name
    self.network_interface = network_interface
Run Code Online (Sandbox Code Playgroud)

我不明白这个定义," network_interface "应该是什么.它是一个字符串,如" eth0 "还是一个类NetworkInterface的实例?我正在考虑解决这个问题的唯一方法是使用" docstring " 记录代码.像这样的东西:

class Host(object):
  ''' Attributes:
      @name: a string
      @network_interface: an instance of class NetworkInterface'''
Run Code Online (Sandbox Code Playgroud)

或者可能有类似的事情的名称约定?

Ned*_*der 22

使用动态语言会教你一些关于静态语言的东西:你从动态语言中现在想念的静态语言中获得的所有帮助,它并没有那么有用.

要以静态语言使用您的示例,您应该知道参数是一个字符串,而在Python中则不是.所以在Python中你写了一个docstring.当你写它的时候,你会发现你有更多的话要说,"这是一个字符串".您需要说明字符串中的数据,应该具有的格式,默认值以及错误条件.

然后你意识到你应该为你的静态语言编写所有这些内容.当然,Java会强制你知道它是一个字符串,但是所有这些其他细节都需要指定,你必须用任何语言手动完成这项工作.

  • 唯一的问题是,我遇到的大多数代码都没有评论,如果有的话:(我一开始就非常挣扎python(想要静态输入那么糟糕)但是同意简洁的docstring解决了这个问题.很好的答案. (2认同)

Pet*_*ham 10

文档字符串约定在PEP 257.

这个例子遵循这种格式来指定参数,如果它们重要,你可以添加它们:

def complex(real=0.0, imag=0.0):
    """Form a complex number.

    Keyword arguments:
    real -- the real part (default 0.0)
    imag -- the imaginary part (default 0.0)

    """
    if imag == 0.0 and real == 0.0: return complex_zero
    ...
Run Code Online (Sandbox Code Playgroud)

对于属性的文档字符串(而不是构造函数参数),也有一个被拒绝的PEP.


Ali*_*ell 9

最pythonic的解决方案是用例子来记录.如果可能,请说明对象必须支持哪些操作才能被接受,而不是特定类型.

class Host(object):
  def __init__(self, name, network_interface)
    """Initialise host with given name and network_interface.

    network_interface -- must support the same operations as NetworkInterface

    >>> network_interface = NetworkInterface()
    >>> host = Host("my_host", network_interface)

    """
    ...
Run Code Online (Sandbox Code Playgroud)

此时,请将您的源链接到doctest,以确保您的文档示例在将来继续有效.