Member Avatar for Mouche

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__

These are used to override external functions/methods, for example:

# 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"

There are other uses like __repr__ can be used to give a class dymanic attributes.

Member Avatar for Mouche

what does __cmp__ do?

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:

# 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

Note that Reverse('iterator overload') is really a class instance!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.