View Single Post
Old Jun 2nd, 2006, 9:27 PM   #1
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 2,013
Rep Power: 6 Sane will become famous soon enough
Send a message via MSN to Sane
More Abstract Use Of Class Methods

I'm trying to achieve a simple solution to requiring to pack a value alongside an integer, so it can be easily remembered at a later time.

class keep_index:
    def __init__(self, value, index):
        self.value = str(value)
        self.index = index
        
    def __call__(self):
        return self.index
    
    def __str__(self):
        return self.value

x = keep_index(4, 1)
print x
print x()

As you can see, this works. Printing x, prints out 4. But calling it returns a value I added alongside it. However, it is a string in my example, not an integer. I have tried __int__ instead of __str__ of course. That was my first attempt, but that doesn't work.

Since I got this far by trial and error by dir()'ing some of the classes like "int" and "str", I may be missing something blatantly obvious. Sorry to be a pain.

Another problem, is if I put 'x' inside a list, and print the list, it displays the function address rather then the value of ".value". And I'd rather not change the concept behind how this is working. I believe that packing an "invisible" value alongside the original would work beautifully.
Sane is offline   Reply With Quote