Python Forum
The function of double underscore back and front in a class function name?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
The function of double underscore back and front in a class function name?
#3
To give a eaiser example then is easier to see how special method work.
They give extra behavior to a class,in this case can now use in operator and len().
class MyList:
    def __init__(self, data):
        self.data = data

    def __contains__(self, item):
        return item in self.data

    def __len__(self):
        return len(self.data)
Use Class:
>>> my_list = MyList([1, 2, 3, 4, 5])
>>> my_list.data
[1, 2, 3, 4, 5]
>>> # Now will "in" work,because of __contains__
>>> print(3 in my_list)
True
>>> print(9 in my_list)
False
>>> # len() works because of __len__
>>> len(my_list)
5
In summary, by defining the __contains__ method,
the MandelbrotSet class allows you to use the in operator to check if a complex number is part of the Mandelbrot set.
This makes it easy to check membership in the set with syntax like if c in mandelbrot_set.
Pedroski55 likes this post
Reply


Messages In This Thread
RE: The function of double underscore back and front in a class function name? - by snippsat - Feb-17-2024, 12:48 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  front-end js and back-end python 3lnyn0 0 1,039 Jun-03-2022, 08:51 PM
Last Post: 3lnyn0
  TimeOut a function in a class ? Armandito 1 1,736 Apr-25-2022, 04:51 PM
Last Post: Gribouillis
  Calling a class from a function jc4d 5 1,948 Dec-17-2021, 09:04 PM
Last Post: ndc85430
  Exit function from nested function based on user input Turtle 5 3,057 Oct-10-2021, 12:55 AM
Last Post: Turtle
  a function common to methods of a class Skaperen 7 2,742 Oct-04-2021, 07:07 PM
Last Post: Skaperen
  Tuple generator, and function/class syntax quazirfan 3 4,059 Aug-10-2021, 09:32 AM
Last Post: buran
Question Stopping a parent function from a nested function? wallgraffiti 1 3,753 May-02-2021, 12:21 PM
Last Post: Gribouillis
Question exiting the outer function from the inner function banidjamali 3 3,681 Feb-27-2021, 09:47 AM
Last Post: banidjamali
  Struggling for the past hour to define function and call it back godlyredwall 2 2,296 Oct-29-2020, 02:45 PM
Last Post: deanhystad
  Passing argument from top-level function to embedded function JaneTan 2 2,326 Oct-15-2020, 03:50 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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