Why does “return list.sort()” return None, not the list?

前端 未结 7 723
感情败类
感情败类 2020-11-21 06:55

I\'ve been able to verify that the findUniqueWords does result in a sorted list. However, it does not return the list. Why?

def fin         


        
7条回答
  •  忘了有多久
    2020-11-21 07:30

    Here is an email from Guido van Rossum in Python's dev list explaining why he choose not to return self on operations that affects the object and don't return a new one.

    This comes from a coding style (popular in various other languages, I believe especially Lisp revels in it) where a series of side effects on a single object can be chained like this:

     x.compress().chop(y).sort(z)
    

    which would be the same as

      x.compress()
      x.chop(y)
      x.sort(z)
    

    I find the chaining form a threat to readability; it requires that the reader must be intimately familiar with each of the methods. The second form makes it clear that each of these calls acts on the same object, and so even if you don't know the class and its methods very well, you can understand that the second and third call are applied to x (and that all calls are made for their side-effects), and not to something else.

    I'd like to reserve chaining for operations that return new values, like string processing operations:

     y = x.rstrip("\n").split(":").lower()
    

提交回复
热议问题