Lecture#4
.pdfIterators how to create
class CustomIterable(object):
def __init__(self, *args, **kwargs):
#initialize your object here
def __iter__(self):
return self
def next(self):
#return some value or raise StopIteration
CustomIterable can now be used in loops
Magic methods
what about this __ methods?
Reserved methods with special meaning
for el in lst:
uses
LstClass.__iter__(lst)
obj = SomeClass(args)
uses
SomeClass.__new__(SomeClass, args) and
SomeClass.__init__(obj, args)
Magic methods
dirty secrets of constructors
__init__ is not a constructor (it’s initializer) although it’s usually to treat it as such
except when subclassing immutables
__new__ is an actual constructor
you need it when subclassing immutables
Magic methods be polite
__str__ is used to emulate str() built-in function
__unicode__ is used to emulate unicode() built-in function
__repr__ is used to get a string representation of object (also `obj` and repr() built-in)
Magic methods be a container
__len__ is used to emulate len()
len(cont) -> cont.__len__()
or ContClass.__len__(cont)
__getitem__ is used to emulate obj[key]
obj[key] -> obj.__getitem__(key)
or ObjClass.__getitem__(obj, key)
Magic methods be a container
__setitem__ is used to emulate obj[key]
=value
obj[key] = value ->
obj.__setitem__(key, value)
or ObjClass.__getitem__(obj, key, value)
Magic methods be a container
__delitem__(self, key) : del obj[key]
__iter__(self) : iter(obj) or in loops
__reversed__(self) : reversed(obj)
__contains__(self, item) : item in obj
Magic methods be smart
__setattr__(self, name, value)
Intercept assignment to attribute name
Be aware of infinite recursion!
__getattribute__(self, name)
__getattr__(self, name)
Intercept access to attribute name
Magic methods be callable
__call__(self, ...)
Intercept call on instance
class SomeClass(object):
def __call__(self, *args, **kwargs): do_something
s = SomeClass() s(1,2,3)
Magic methods all together
Magic methods in Python allow you to create classes, which look and behave like built-in types
See this blog post for general overview
http://www.rafekettler.com/magicmethods.html