These are used to override external functions/methods, for example:
[php]# example of methods you can override in classes
class Dollars(object):
def __init__(self,amount):
self.amount = amount
def __repr__(self):
return '$%.2f' % self.amount
def __str__(self):
return '"%s"' % str(self.amount)
a = Dollars(10)
print a # 10
print "The amount is", a # The amount is 10
print "The amount is", repr(a) # The amount is $10.00
print str(a) # "10"
[/php]There are other uses like __repr__ can be used to give a class dymanic attributes.
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
With __cmp__() you can override, overload, customize (whatever you want to call it) the cmp() function for the class instance. There are a bunch of these babies, all starting and ending with double underlines. I think they are also called instance methods. They can do powerful things, but also can make your code a bitch to read and comprehent.
Here is one that hijacks the iterator used by a for loop:
[php]# operator overloading with instance method __iter__()
class Reverse(object):
"""custom iterator for looping over a sequence backwards
sort of hijacks the iterator used by the for loop
uses __iter__(self) and next(self) to do the trick"""
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
for c in Reverse('iterator overload'):
print c, # d a o l r e v o r o t a r e t i
[/php]Note that Reverse('iterator overload') is really a class instance!
Ene Uran
Posting Virtuoso
1,723 posts since Aug 2005
Reputation Points: 625
Solved Threads: 213