1

I have two examples:

a = [1,2,3]
b = 4

print (a.__len__())
print (len(a))

print(b.__add__(4))
print (b + 4)

I guess my question is, is there a difference when using __len__ magic method versus the built in len() method? The only time I see people use __len__ is when trying to trying to find the length of an object of a user-created class.

Same with other dunder methods, such as __str__, or __add__ I never seem them used outside of a class or OOP in general.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
dyao
  • 983
  • 3
  • 12
  • 25
  • [yes, there is](http://stackoverflow.com/questions/1712227/how-to-get-the-size-of-a-list#comment18340392_1712236) – jfs Oct 09 '15 at 05:25
  • The point of the "magic methods" is to let you customise how your object behaves when used with normal syntax. Sure, you could rewrite every `foo = bar + baz` as `foo = `bar.__add__(baz), but why would you?! Also, I don't think that would invoke delegation where that method isn't implemented, which `+` does. – jonrsharpe Oct 09 '15 at 06:55

1 Answers1

-2

There are only small differencies. Function is just a function, that call len. Something like

def len(x):
   return x.__len__()

Of course, you can override builtin len, but that is dump (maybe except debugging). Only different thing is len(x) is easier to read, and x.__len__ allows you create your own implentation of operator. x.__len__ also can be bit faster, but it is a good reason to use it.

When operator have 2 arguments its implementation do more. a+b at first it tries, whether is callable a.__add__ and if it is not, than tries to call b.__radd__.

lofcek
  • 1,165
  • 2
  • 9
  • 18
  • [Why Python function `len` is faster than `__len__` method?](http://stackoverflow.com/questions/20302558/why-python-function-len-is-faster-than-len-method) – AXO Feb 14 '17 at 00:54