Apr-27-2019, 12:07 PM
Apr-27-2019, 12:36 PM
Considering it causes an error, it's probably not optimal. I think you mean word.__len__(). I have never seen anyone use that. It might be slightly more efficient, but it would be the most minimal efficiency gain you could make in Python. Besides, the whole point of word.__len__ is so that the len function can use it.
Apr-27-2019, 01:17 PM
The methods are called Magic Methods or Dunder Methods (double under).
This methods are called by types:
int()
float()
bool()
len()
list()
... and more
If you want to implement a special behaviour of an object, you use the dunder methods for it.
For example you have a class with for a card deck. You can implement the method __len__ to return the amout of cards:
Pro Tip: Look for iter() and __iter__
If you implement this method, your Object supports iteration.
The iterator protocol is one of most powerful features in Python.
This methods are called by types:
int()
float()
bool()
len()
list()
... and more
If you want to implement a special behaviour of an object, you use the dunder methods for it.
For example you have a class with for a card deck. You can implement the method __len__ to return the amout of cards:
class Deck: def __init__(self, cards): self.cards = cards def __len__(self): return len(self.cards) # then make an instance of the class cards = Deck([1,2,3]) # then use the len function print(len(cards))len(object) calls object.__len__() in a high level view.
Pro Tip: Look for iter() and __iter__
If you implement this method, your Object supports iteration.
The iterator protocol is one of most powerful features in Python.