954,549 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

class (builtin?) methods

hey... I wasn't able to find much information on these class methods other than __init__ ... could you explain what these (and maybe some others) do or perhaps just give me a link to a page that explains them:

def __repr__
def __str__
def __cmp__

LaMouche
Posting Whiz in Training
269 posts since Oct 2006
Reputation Points: 83
Solved Threads: 39
 

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
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

what does __cmp__ do?

LaMouche
Posting Whiz in Training
269 posts since Oct 2006
Reputation Points: 83
Solved Threads: 39
 

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
 

Okay, thanks.

I found this page to be helpful.

http://docs.python.org/lib/built-in-funcs.html

LaMouche
Posting Whiz in Training
269 posts since Oct 2006
Reputation Points: 83
Solved Threads: 39
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You