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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!