Reference: http://www.rafekettler.com/magicmethods.html
Add magic to your classes
Surrounded by __
__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?
__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")
- static method
- has to return new object
- need to call the super objects new method
!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.
!python
>>> 1 + 2
>>> 1 == 1
>>> 1 > 2
>>> # wont work
>>> custom_object == another_object
__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, >=.
- override operators like
+
,-
etc for your object.
!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
!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)