Python Forum
Optimal Statements in Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Optimal Statements in Python
#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


Messages In This Thread
Optimal Statements in Python - by dukoolsharma - Apr-27-2019, 12:07 PM
RE: Optimal Statements in Python - by ichabod801 - Apr-27-2019, 12:36 PM
RE: Optimal Statements in Python - by DeaD_EyE - Apr-27-2019, 01:17 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Optimal way to search partial correspondence in a large dict genny92c 0 1,023 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,199 Aug-05-2020, 04:41 PM
Last Post: bntayfur
  Understanding if Statements in Python Kathleen 1 2,470 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