简体   繁体   English

Python代码的可读性

[英]Python code readability

I have a programming experience with statically typed languages. 我有使用静态类型语言的编程经验。 Now writing code in Python I feel difficulties with its readability. 现在用Python编写代码时,我很难理解它的可读性。 Lets say I have a class Host : 可以说我有一个班级主持人

class Host(object):
  def __init__(self, name, network_interface):
    self.name = name
    self.network_interface = network_interface

I don't understand from this definition, what " network_interface " should be. 从这个定义中我不明白什么是“ network_interface ”。 Is it a string , like " eth0 " or is it an instance of a class NetworkInterface ? 它是一个字符串 ,例如“ eth0 ”,还是类NetworkInterface的实例? The only way I'm thinking about to solve this is a documenting the code with a " docstring ". 我正在考虑解决此问题的唯一方法是使用“ docstring ”记录代码。 Something like this: 像这样:

class Host(object):
  ''' Attributes:
      @name: a string
      @network_interface: an instance of class NetworkInterface'''

Or may be there are name conventions for things like that? 还是可能有诸如此类的名称约定?

Using dynamic languages will teach you something about static languages: all the help you got from the static language that you now miss in the dynamic language, it wasn't all that helpful. 使用动态语言会教给您一些有关静态语言的知识:从静态语言中获得的所有帮助(您现在在动态语言中会错过的)并不是那么有用。

To use your example, in a static language, you'd know that the parameter was a string, and in Python you don't. 在静态语言中使用示例时,您会知道参数是一个字符串,而在Python中则不是。 So in Python you write a docstring. 因此,在Python中,您编写了一个文档字符串。 And while you're writing it, you realize you had more to say about it than, "it's a string". 而且,当您编写它时,您意识到您要说的不仅仅是“这是一个字符串”。 You need to say what data is in the string, and what format it should have, and what the default is, and something about error conditions. 您需要说出字符串中包含哪些数据,数据应具有的格式,默认值为什么以及有关错误情况的信息。

And then you realize you should have written all that down for your static language as well. 然后您意识到您也应该将所有静态语言都写下来。 Sure, Java would force you know that it was a string, but there's all these other details that need to be specified, and you have to manually do that work in any language. 当然,Java会迫使您知道它是一个字符串,但是还需要指定所有其他详细信息,因此您必须使用任何语言手动进行此操作。

The docstring conventions are at PEP 257 . 文档字符串约定位于PEP 257

The example there follows this format for specifying arguments, you can add the types if they matter: 此处的示例使用以下格式指定参数,可以在需要时添加类型:

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
    ...

There was also a rejected PEP for docstrings for attributes ( rather than constructor arguments ). 对于属性(而不是构造函数参数)的文档字符串,还有一个拒绝的PEP。

The most pythonic solution is to document with examples. 最pythonic的解决方案是用示例记录。 If possible, state what operations an object must support to be acceptable, rather than a specific type. 如果可能,请说明对象必须支持的操作才能接受,而不是指定特定类型。

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)

    """
    ...

At this point, hook your source up to doctest to make sure your doc examples continue to work in future. 此时,将您的源代码连接到doctest ,以确保您的doc示例在将来继续运行。

Personally I found very usefull to use pylint to validate my code. 我个人认为使用pylint验证我的代码非常有用。

If you follow pylint suggestion almost automatically your code become more readable, you will improve your python writing skills, respect naming conventions. 如果您遵循pylint的建议几乎自动使您的代码更具可读性,那么您将提高python的写作技巧,并遵守命名约定。 You can also define your own naming conventions and so on. 您还可以定义自己的命名约定,等等。 It's very useful specially for a python beginner. 特别是对于python初学者来说,这非常有用。

I suggest you to use. 我建议您使用。

Python, though not as overtly typed as C or Java, is still typed and will throw exceptions if you're doing things with types that simply do not play nice together. Python虽然没有像C或Java那样公开地键入,但仍然会被键入,并且如果您使用的类型根本不能很好地配合使用,则会抛出异常。

To that end, if you're concerned about your code being used correctly, maintained correctly, etc. simply use docstrings, comments, or even more explicit variable names to indicate what the type should be. 为此,如果您担心代码的正确使用,正确维护等,只需使用文档字符串,注释或什至更明确的变量名来指示类型。

Even better yet, include code that will allow it to handle whichever type it may be passed as long as it yields a usable result. 更好的是,包括允许其处理可能传递的任何类型的代码,只要它产生可用的结果即可。

One benefit of static typing is that types are a form of documentation. 静态类型化的一个好处是类型是文档的一种形式。 When programming in Python, you can document more flexibly and fluently. 使用Python编程时,您可以更灵活,更流畅地编写文档。 Of course in your example you want to say that network_interface should implement NetworkInterface, but in many cases the type is obvious from the context, variable name, or by convention, and in these cases by omitting the obvious you can produce more readable code. 当然,在您的示例中,您想说的是network_interface应该实现NetworkInterface,但是在许多情况下,从上下文,变量名或按照约定来看,类型是显而易见的,并且在这些情况下,通过省略显而易见的代码,您可以生成更具可读性的代码。 Common is to describe the meaning of a parameter and implicitly giving the type. 常见的是描述参数的含义并隐式给出类型。

For example: 例如:

def Bar(foo, count):
    """Bar the foo the given number of times."""
    ...

This describes the function tersely and precisely. 简洁,准确地描述了该功能。 What foo and bar mean will be obvious from context, and that count is a (positive) integer is implicit. 从上下文中可以明显看出foo和bar的含义,而count是一个(正)整数是隐式的。

For your example, I'd just mention the type in the document string: 对于您的示例,我只想在文档字符串中提及类型:

"""Create a named host on the given NetworkInterface."""

This is shorter, more readable, and contains more information than a listing of the types. 它比类型列表短,更易读,并且包含更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM