为什么要在全局范围内提供一些默认方法,例如 len 函数,而不是在实例级别提供它们,例如:
list.len()
代替:
len (list)
我发现像 len 这样的方法比实例方法更难发现。
这背后有什么原因吗?
请您参考如下方法:
这个问题与this one非常相似.答案是一样的:
因为 Python 的创造者 Guido van Rossum 认为前缀表示法在某些情况下更具可读性。 Here是完整的答案。我要引用一些部分:
(a) For some operations, prefix notation just reads better than postfix -- prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a formula like x*(a+b) into xa + xb to the clumsiness of doing the same thing using a raw OO notation.
(b) When I read code that says len(x) I know that it is asking for the length of something. This tells me two things: the result is an integer, and the argument is some kind of container. To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len(). Witness the confusion we occasionally have when a class that is not implementing a mapping has a get() or keys() method, or something that isn't a file has a write() method.
Saying the same thing in another way, I see 'len' as a built-in operation. I'd hate to lose that. I can't say for sure whether you meant that or not, but 'def len(self): ...' certainly sounds like you want to demote it to an ordinary method. I'm strongly -1 on that.
