The built-in 1 function works on some objects, but not on others. Only things that have a length work with the 1 function.Lists, sets, dictionaries, strings, and most data structures in Python have a length:
But numbers don't:
When making a class in Python, you can control whether instances of that class have a length. Python's built-in 1 function calls the 6 method (pronounced "dunder 1") on the object you give it.So if that object has a 6 method, it has a length:
If it doesn't have a 6 method, the 1 function raises a 1 instead:
How to make instances of your class have a length?Python's 2 module has a function ( 3) which can randomly select an item from a given sequence.
This 3 function only works on objects that can be indexed and have a length.Here we have a class named 5:
This class has a 6 method and a 7 method. That 7 method allows instances of this class to be indexed using square brackets ( 9).But this isn't quite enough to allow our 5 objects to work with the 1 function. If we pass a 5 object to the 1 function, we'll get an error:
Python gives us an error because 5 objects don't have a length, which the 1 function requires. These objects don't work with the built-in 1 function:
In order to support the built-in 1 function, we can add a 6 method to this class:
Now instances of this class have a length:
And they also work with 1: 0SummaryYou can make your objects work with the built-in 1 function by adding a 6 method to them. You'll pretty much only ever add a 6 method if you're making a custom data structure, like a sequence or a mapping. |