It's often the case that the "typical" behavior of a built-in or operator is to call [with different and nicer syntax] suitable magic methods [ones with names like __whatever__
] on the objects involved. Often the built-in or operator has "added value" [it's able to take different paths depending on the objects involved] -- in the case of len
vs __len__
, it's just a bit of sanity checking on the built-in that is missing from the magic method:
>>> class bah[object]:
... def __len__[self]: return "an inch"
...
>>> bah[].__len__[]
'an inch'
>>> len[bah[]]
Traceback [most recent call last]:
File "", line 1, in
TypeError: 'str' object cannot be interpreted as an integer
When you see a
call to the In the following example, you create a custom class If you hadn’t defined the If you call Here’s the error message: The result of len
built-in, you're sure that, if the program continues after that rather than raising an exception, the call has returned an integer, non-negative, and >> friends = ['Alice', 'Bob', 'Carl', 'Ann']
>>> len[friends]
4
>>> friends.extend[[1, 2, 3]]
>>> len[friends]
7
>>> len['hello world']
11
>>> len['hi']
2
>>> len[[1, 2, 3]]
3
>>> len[{42, 21}]
2
>>> age = {'Alice': 18, 'Bob': 21}
>>> len[age]
2
>>> age['Carl'] = 33
>>> len[age]
3
Example Custom __len__[]
Data
and overwrite the __len__[]
method so that it returns a dummy number.class Data:
def __len__[self]:
return 42
a = Data[]
print[len[a]]
# 42
print[bool[a]]
# True --> Because 42 != 0
__len__[]
method, Python would’ve raised an error:Default __len__[] Implementation
len[x]
on an object on which the x.__len__[]
dunder method is not defined, Python will raise a TypeError: object of type '...' has no len[]
. To fix this error, simply define the __len__[]
method in the class definition before calling len[]
on an object.class Data:
pass
a = Data[]
print[len[a]]
Traceback [most recent call last]:
File "C:\Users\xcent\Desktop\code.py", line 7, in
print[len[a]]
TypeError: object of type 'Data' has no len[]
What’s
the Difference Between len[x] and x.__len__[]?
len[x]
and x.__len__[]
is the same: both return the number of elements in the object, i.e., more generally, its length.
Have a look at this example:
>>> len[[1, 2, 3]] 3 >>> [1, 2, 3].__len__[] 3
The difference between len[x]
and x.__len__[]
is only syntactical sugar. The former built-in function
calls the latter method internally to implement the correct behavior. So, there’s no semantic difference between both ways to obtain the length of an object.
References:
- //docs.python.org/3/reference/datamodel.html
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
Join the free webinar now!
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners [NoStarch 2020], coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.