Python Forum
Optimal Statements in Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Optimal Statements in Python
#1
I am bit confused whether the below statements are optimal or not? Need help!
word= 'word'
print(word._len_())
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Optimal way to search partial correspondence in a large dict genny92c 0 1,013 Apr-22-2022, 10:20 AM
Last Post: genny92c
  RuntimeError: Optimal parameters not found: Number of calls to function has reached m bntayfur 0 6,166 Aug-05-2020, 04:41 PM
Last Post: bntayfur
  Understanding if Statements in Python Kathleen 1 2,449 Mar-05-2019, 07:55 PM
Last Post: Yoriz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020