Most of this talk is about __ methods. Generally, you don't need to know this. But occasionally you do.
The __init__ method is used to initialize a class instance with specific things, like a constructor in c++.
The default __init__ method is empty:
class Test:
def __init__(self):
pass
One of the traditional things is to set up the internal variables:
class Test:
def __init__(self):
self.a = 10
self.b = 20
We can also take arguments, just like a normal function:
class Test:
def __init__(self,a,b=20):
self.a = a
self.b = b
This class can then be instantiated in any of these ways:
test1 = Test(10)
test2 = Test(12,14)
test3 = Test(12,b=14)
test4 = Test(a=12,b=14)
The __del__ method is the compliment to __init__ and is called on destruction of the object. Note that it is not called when you do del x; it is actually called when garbage collected.
Generally, you do not need to define this yourself. Most objects inside the class will clean up after themselves when the object is deleted. Only when you really need to do a manual cleanup is the __del__ method required.
The __str__ method is called when the str(object) method is called on an object. The goal is to translate the object into a human readable form.
__repr__ on the other hand is designed to be machine readable. It is sometimes used as a simplistic serialization, and should contain enough information to comletely reconstruct the object.
The __len__ method is called when doing len(object).
The __getitem__ method is called for getting a value via a key: object[key]. __setitem__ and __delitem__ perform corresponding functions.
__iter__ returns an iterator for the container, which is helpful for for loops.
__contains__ defines behavior for testing using the in operator. Note that if you don't define this, python will just iterate over the entire container to search for items.
Comparison defaults to __hash__, which defaults to the memory address of the object. If your class is actually comparable, define some of the below functions.
__cmp__ is the old standby, though not recommended anymore:
class my_int:
def __init__(self,i):
self.i = i
def __cmp__(self,other):
return self.i - other.i
__eq__, __ne__, __lt__, __gt__, __le__, __ge__
These are the preferred way to define comparisons. You can specify each comparison operator individually, but (in 2.7+) you only need to define __eq__ and __lt__ or __gt__ and python will fill in the rest:
class my_int:
def __init__(self,i):
self.i = i
def __eq__(self,other):
return self.i == other.i
def __lt__(self,other):
return self.i < other.i
A context manager is a way to handle cleanup of an object automatically. The typical example is a file:
with open('myfile','w') as f:
f.write('some data')
f.write('more data')
Once you exit the context the file will be automatically closed, even if there is an exception. This is similar to writing your own try finally.
Rewriting the file context manager:
def open_file(*args):
f = open(*args)
try:
yield f
finally:
f.close()
A context manager can also be a class:
class open_file:
def __init__(self,*args):
self.f = open(*args)
def __enter__(self):
return self.f
def __exit__(self, exception_type, exception_value, traceback):
# if exception is raised, the arguments will not be None
self.f.close()
This doc gives a good overview of all the special methods: