[Tutor] how to get str() to use my function?

Alex Hall mehgcap at gmail.com
Wed Aug 4 18:11:04 CEST 2010


Thanks, and I also see what I did wrong with my __eq__ function.

On 8/4/10, Huy Ton That <huyslogic at gmail.com> wrote:
> These are special method names.
>
> View section 3.4 and below here
>
> http://docs.python.org/reference/datamodel.html
>
> On Wed, Aug 4, 2010 at 11:37 AM, Alex Hall <mehgcap at gmail.com> wrote:
>
>> It worked, thanks. Is there a list of these functions somewhere? That
>> is, the functions that map implicitly to operators or implied uses?
>> For example, printing will call __str__, as will a cal to str(). What
>> about math or comparison operators? I have heard of __eq__, __gt__,
>> and so on, but I tried to implement one and I got an error saying that
>> it required three arguments. It did, but only because the first was
>> self. I put the function inside my card class:
>>  def __eq__(self, card1, card2):
>>  return(card1.rank==card2.rank)
>>  #end def __eq__
>> For some reason it is still looking for three arguments...
>>
>>
>> On 8/4/10, Huy Ton That <huyslogic at gmail.com> wrote:
>> > You could write __str__ function
>> >
>> >>>> class card(object):
>> > ...     def __init__(self, card1, card2):
>> > ...             self.card1, self.card2 = card1, card2
>> > ...     def __str__(self):
>> > ...             return str(str(self.card1)+','+str(self.card2))
>> > ...
>> >>>> a = card(0,0)
>> >>>> str(a)
>> > '0,0'
>> >
>> > On Wed, Aug 4, 2010 at 10:37 AM, Alex Hall <mehgcap at gmail.com> wrote:
>> >
>> >> Hi all,
>> >> I have a card class. A card object simply consists of a pair of
>> >> numbers; 0,0 might be the ace of clubs, for example. I have a toString
>> >> method in my card class. Is there a way to just say str(card) instead
>> >> of card.toString()? Maybe some sort of basic, built-in function to
>> >> override? TIA. Oh, what about doing the same with operators? For
>> >> example, could I get the program to call my own math functions when it
>> >> sees a card object in a math expression, like
>> >> if(card1==card2)
>> >>
>> >> --
>> >> Have a great day,
>> >> Alex (msg sent from GMail website)
>> >> mehgcap at gmail.com; http://www.facebook.com/mehgcap
>> >> _______________________________________________
>> >> Tutor maillist  -  Tutor at python.org
>> >> To unsubscribe or change subscription options:
>> >> http://mail.python.org/mailman/listinfo/tutor
>> >>
>> >
>>
>>
>> --
>> Have a great day,
>> Alex (msg sent from GMail website)
>> mehgcap at gmail.com; http://www.facebook.com/mehgcap
>>
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap


More information about the Tutor mailing list