Is arr.__len__() the preferred way to get the length of an array in Python?

前端 未结 8 1009
悲哀的现实
悲哀的现实 2020-12-04 05:18

In Python, is the following the only way to get the number of elements?

arr.__len__()

If so, why the strange syntax?

相关标签:
8条回答
  • 2020-12-04 05:43

    The preferred way to get the length of any python object is to pass it as an argument to the len function. Internally, python will then try to call the special __len__ method of the object that was passed.

    0 讨论(0)
  • 2020-12-04 05:45

    The way you take a length of anything for which that makes sense (a list, dictionary, tuple, string, ...) is to call len on it.

    l = [1,2,3,4]
    s = 'abcde'
    len(l) #returns 4
    len(s) #returns 5
    

    The reason for the "strange" syntax is that internally python translates len(object) into object.__len__(). This applies to any object. So, if you are defining some class and it makes sense for it to have a length, just define a __len__() method on it and then one can call len on those instances.

    0 讨论(0)
提交回复
热议问题