Skip to content

Instantly share code, notes, and snippets.

@vigneshsarma
Created June 21, 2014 14:42
Show Gist options
  • Save vigneshsarma/bf5f664d8d053890e5f7 to your computer and use it in GitHub Desktop.
Save vigneshsarma/bf5f664d8d053890e5f7 to your computer and use it in GitHub Desktop.
June Bangpypers meetup - Magic Methods - Python
# comparison
from functools import total_ordering
@total_ordering
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return self.name == other.name and self.age == other.age
def __gt__(self, other):
return self.age > other.age
# def __lt__(self, other):
# return
# __init__
class Person(object):
def __init__(self, name):
self.name = name
# __new__
class Person(object):
def __new__(cls, *args, **kwargs):
print "args:", args, "kwargs:", kwargs
inst = object.__new__(cls, *args, **kwargs)
print "instance:", inst, "class:", cls
return inst
def __init__(self, name):
print "in init"
self.name = name
# representations
class Person(object):
def __init__(self, name):
self.name = name
def __str__(self):
print "str"
return 'Person: ' + self.name
def __repr__(self):
print "repr"
return 'Person("' + self.name + '")'
def __unicode__(self):
return u'Person utf: ' + self.name
# sequences
from collections import defaultdict
class ContactBook(object):
version = '0.1'
def __init__(self):
self.objects = []
def add(self, contact):
self.objects.append(contact)
def all(self):
return self.objects
def index(self):
d = defaultdict(list)
for contact in self.all():
d[contact[0].lower()].append(contact)
return d
def __iter__(self):
for item in self.all():
yield item
def __getitem__(self, key):
if isinstance(key, int):
return self.all()[key]
else:
return self.index()[key]
def __setitem__(self, key, value):
pass
def __len__(self):
return len(self.all())
def __enter__(self):
return self
def __exit__(self, )

Magic Methods - Python

Vignesh Sarma


What are magic methods?

Reference: http://www.rafekettler.com/magicmethods.html

Add magic to your classes

Surrounded by __


Object Initialization

__init__

!python
class Person(object):
    def __init__(self, name):
        self.name = name
  • Only initializes
  • does not create
  • similar to constructor in other languages
  • but who created the object?

Object creation

__new__

!python
class Person(object):

    def __new__(cls, *args, **kwargs):
        print "args:", args, "kwargs:", kwargs
        inst = object.__new__(cls, *args, **kwargs)
        print "instance:", inst, "class:", cls
        return inst

    def __init__(self, name):
        print "in init"
        self.name = name

In [0]: Person(name="hi")


__new__

  • static method
  • has to return new object
  • need to call the super objects new method

Representations

!python
class Person(object):

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return 'Person: ' + self.name

    def __repr__(self):
        return 'Person("' + self.name + '")'
  • str for humans.
  • repr for programs.

Operators

!python
>>> 1 + 2
>>> 1 == 1
>>> 1 > 2
>>> # wont work
>>> custom_object  == another_object

Comparison

  • __cmp__(self, other) for all comparisons.
  • __eq__(self, other) equality operator, ==.
  • __ne__(self, other) inequality operator, !=.
  • __lt__(self, other) less-than operator, <.
  • __gt__(self, other) greater-than operator, >.
  • __le__(self, other) less-than-or-equal-to operator, <=.
  • __ge__(self, other) greater-than-or-equal-to operator, >=.

Arithmetic Operators

  • override operators like +, - etc for your object.

Sequences

!python
class ContactBook(object):
    version = '0.1'

    def __init__(self):
        self.objects = []

    def add(self, contact):
        self.objects.append(contact)

    def all(self):
        return self.objects

    def index(self):
        d = defaultdict(list)
        for contact in self.all():
            d[contact[0].lower()].append(contact)
        return d

Context Managers

!python
with open('foo.txt') as bar:
    print bar.read()

Equvalent to

!python
bar = open(foo.txt)
try:
    print bar.read()
finally:
    bar.close()
  • enter(self)
  • exit(self, exception_type, exception_value, traceback)

END

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