Python Forum

Full Version: Optimal Statements in Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am bit confused whether the below statements are optimal or not? Need help!
word= 'word'
print(word._len_())
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.
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:



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.