Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

sorting - How does python compare functions?

How come this doesn't rise Attribute error? function object doesn't have any of the comparison methods. Does it use id() somehow?

fun1 = lambda:x
fun2 = lambda:x
print fun1 == fun1 # True
print fun1 == fun2 # False
print fun1 > fun2 # True
print fun1 < fun2 # False
print fun1 > 1 # True

I understand that it compares addresses, but how? Is it some low level hack in to intercept __lt__, __eq__ etc. ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Function objects do not define their own comparisons or rich comparisons. Instead, they inherit from type objects which implement rich comparisons based on the object's address in memory.

So yes, it effectively uses addresses just like the built-in id() function does.

In Python 3, functions are no longer orderable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...