在《Fluent Python》里看到Why len is not method，有些困惑，于是开始找答案。
在Python词汇表里，对函数和方法有如下说明 function: A series of statements which returns some value to a caller. It can also be passed zero or more arguments which may be used in the execution of the body.
method: A function which is defined inside a class body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called self).
An object is hashable if it has a hash value which never changes during its lifetime (it needs a hash() method), and can be compared to other objects (it needs an eq() method). Hashable objects which compare equal must have the same hash value.
>>> import registration running register(<function f1 at 0x10063b1e0>) running register(<function f2 at 0x10063b268>) >>> registration.registry [<function f1 at 0x10063b1e0>, <function f2 at 0x10063b268>]
1 2 3 4 5 6 7 8 9 10 11
import time def clock(func): def clocked(*args): # t0 = time.perf_counter() result = func(*args) # elapsed = time.perf_counter() - t0 name = func.__name__ arg_str = ', '.join(repr(arg) for arg in args) print('[%0.8fs] %s(%s) -> %r' % (elapsed, name, arg_str, result)) returnresult return clocked
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
import time from clockdeco import clock @clock defsnooze(seconds): time.sleep(seconds)
@clock deffactorial(n): return1if n < 2else n*factorial(n-1)