Skip to content

Instantly share code, notes, and snippets.

@hkulekci
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hkulekci/c5ea5b9bed17eb30167d to your computer and use it in GitHub Desktop.
Save hkulekci/c5ea5b9bed17eb30167d to your computer and use it in GitHub Desktop.
Python Magic Methods Notes => http://www.rafekettler.com/magicmethods.html

Python Magic Methods

Construction and Inıtıalization

__new__ : First run this methos when the class object is created!

__init__ : Construtor of a class. You can send parameter to your class with __init__ method.

__del__ : Deconstructor method of the class. But this method is not secure to use a garbage collector. It is not guarantee when the object is deleted.

from os.path import join

class FileObject:
    '''Wrapper for file objects to make sure the file gets closed on deletion.'''

    def __init__(self, filepath='~', filename='sample.txt'):
        # open a file filename in filepath in read and write mode
        self.file = open(join(filepath, filename), 'r+')

    def __del__(self):
        self.file.close()
        del self.file

Comparison Magic Method

__cmp__ : compare opeartiob method for an object

__eq__ : equality operation method for a object

__ne__ : not equeal

__lt__ : less-than

__gt__ : greater-than

__le__ : less-then-or-equal

__ge__ : greater-then-or-equal

class Word(str):
    '''Class for words, defining comparison based on word length.'''

    def __new__(cls, word):
        # Note that we have to use __new__. This is because str is an immutable
        # type, so we have to initialize it early (at creation)
        if ' ' in word:
            print "Value contains spaces. Truncating to first space."
            word = word[:word.index(' ')] # Word is now all chars before first space
        return str.__new__(cls, word)

    def __gt__(self, other):
        return len(self) > len(other)
    def __lt__(self, other):
        return len(self) < len(other)
    def __ge__(self, other):
        return len(self) >= len(other)
    def __le__(self, other):
        return len(self) <= len(other)

Numerical Magic Methods

__pos__ : implement behaviour for unary positive (eg.: +some_object)

__neg__ : implement behaviour for negation (eg.: -some_object)

__abs__ : implement behaviour for built-in abs() function

__invert__ : implement behaviour for bitwise invertion (eg.: ~some_object)

__round__ : implement behaviour for built-in round() function

__floor__ :

__ceil__ :

__trunc__ :

Normal Arithmetic Operations

__add__ : implement addition

__sub__ : implement substract

__mul__ : implement multiplication

__floordiv__ : implement integer division with // operator

__div__ : implement division with / operator

__truediv__ : Implements true division. Note that this only works when from __future__ import division is in effect.

__mod__: implement modulo with % operator

__divmod__ : Implements behavior for long division using the divmod() built in function.

__pow__ : implement exponention, using with ** operator

__lshift__ : implement bitwise left shifting, usng with << operator

__rshift__ : implement bitwise right shifting, usng with >> operator

__and__ : implement bitwise and operator, using with & operator

__or__ : implement bitwise or, using with | opeartor

__xor__ : implement bitwise xor, using with ^ operator

Reflected Arithmetic Operations

You can use addition like that some_object + other_object on Normal Arithmetic Operation. The same thing, with Reflected Arithmetic Operation, you can use like that other_object + some_object. In two example, magis operator function is in some_object object class.

__radd__ : implement addition

__rsub__ : implement substract

__rmul__ : implement multiplication

__rfloordiv__ : implement integer division with // operator

__rdiv__ : implement division with / operator

__rtruediv__ : Implements true division. Note that this only works when from __future__ import division is in effect.

__rmod__: implement modulo with % operator

__rdivmod__ : Implements behavior for long division using the divmod() built in function.

__rpow__ : implement exponention, using with ** operator

__rlshift__ : implement bitwise left shifting, usng with << operator

__rrshift__ : implement bitwise right shifting, usng with >> operator

__rand__ : implement bitwise and operator, using with & operator

__ror__ : implement bitwise or, using with | opeartor

__rxor__ : implement bitwise xor, using with ^ operator

Augmented assignment

__iadd__ : implement addition

__isub__ : implement substract

__imul__ : implement multiplication

__ifloordiv__ : implement integer division with // operator

__idiv__ : implement division with / operator

__itruediv__ : Implements true division. Note that this only works when from __future__ import division is in effect.

__imod__: implement modulo with % operator

__idivmod__ : Implements behavior for long division using the divmod() built in function.

__ipow__ : implement exponention, using with ** operator

__ilshift__ : implement bitwise left shifting, usng with << operator

__irshift__ : implement bitwise right shifting, usng with >> operator

__iand__ : implement bitwise and operator, using with & operator

__ior__ : implement bitwise or, using with | opeartor

__ixor__ : implement bitwise xor, using with ^ operator

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment