0
what's wrong in calling list.len() rather len(list) .?? why python defined len() just as a normal method unlike those with dot operator ?
2 Antworten
+ 1
Simply because there is no attribute len for a list object. Was it on whim that it wasn't made an attribute of a list object? Maybe, but it makes sense not to. Lists aren't the only things that need to have their contents counted. Tuples, dictionaries, strings etc may need to have their contents counted. So it may have been easier to make a function that could count the length of those objects rather than make a method for each of those objects.
Strings however do have the method __len__(). Which is accessible by using the len() function on a string object.
Sound weird, I actually don't know why that is the case, but I figure it was make the feature less OOP and more procedural.
+ 1
list.len() assumes that len() is a method in the class called list, if you created a list object then you could use the len() method on it using the "dot" operator, if len() is a method created in the main method then it is not connected to an object or class therefore it must be used on its own with relative parameters (if there are any), also if list is not an object the you cannot call a method on it using the dot operator
(i am new to Python i am assuming this is fairly similar to Java)