Magic method

From CS 61A Wiki
Jump to: navigation, search

In Python, a magic method is a special method surrounded by double underscores that is invoked when you use certain syntax.

__init__

__init__ is called when you call a class to create an instance.

__iter__ and __next__

__iter__ and __next__ implement the iterator protocol.

__getitem__ and __len__

__getitem__ and __len__ implement the sequence protocol.

__len__ is called by len, and __getitem__ is called when you index into a sequence. Example:

class Link:
    """
    >>> lst = Link(1, Link(2, Link(3)))
    >>> lst[1] # calls lst.__getitem__(1)
    2
    >>> len(lst) # calls lst.__len__()
    3
    """
    empty = None
 
    def __init__(self, first, rest=empty):
        self.first = first
        self.rest = rest
 
    def __len__(self):
        if self.rest is not Link.empty:
            return 1 + len(self.rest)
        return 1
 
    def __getitem__(self, i):
        if i == 0:
            return self.first
        elif self.rest is not Link.empty:
            return self.rest[i - 1]
        else:
            raise StopIteration

__str__ and __repr__

__str__ and __repr__ implement the string representation protocol.

The repr string is Python-readable, while the str string is human-readable. repr is what Python displays in an interactive session, and str is what Python prints using the print function.[1]

Example:

class Link:
    """
    >>> lst = Link(1, Link(2, Link(3)))
    >>> lst # calls lst.__repr__()
    Link(1, Link(2, Link(3)))
    >>> print(lst) # calls lst.__str__()
    < 1 2 3 >
    """
    empty = None
 
    def __init__(self, first, rest=empty):
        self.first = first
        self.rest = rest
 
    def __repr__(self):
        if self.rest is Link.empty:
            rest = ''
        else:
            rest = ', ' + repr(self.rest)
        return 'Link({}{})'.format(self.first, rest)
 
    def __str__(self):
        if self.rest is Link.empty:
            rest = ''
        else:
            rest = ' ' + str(self.rest)[2:-2]
        return '< {}{} >'.format(self.first, rest)

Sources

  1. http://inst.eecs.berkeley.edu/~cs61a/su14/lecture/15/without_animation.pdf