Fwd: class print method...
Lie Ryan
lie.1296 at gmail.com
Mon Dec 5 07:41:25 EST 2011
On 12/05/2011 10:18 PM, Suresh Sharma wrote:
>
> Pls help its really frustrating
> ---------- Forwarded message ----------
> From: Suresh Sharma
> Date: Monday, December 5, 2011
> Subject: class print method...
> To: "d at davea.name <mailto:d at davea.name>" <d at davea.name
> <mailto:d at davea.name>>
>
>
> Dave,
> Thanx for the quick response, i am sorry that i did not explain
> correctly look at the code below inspite of this i am just getting class
> object at memory location.I am sort i typed all this code on my android
> in a hurry so.indentation could.not.be.managed but this.similar code
> when i run all my objects created by class deck are not shown but stored
> in varioia meory locations. How can i display them.
>
I think you're in the right track, however I suspect you're running the
code in the shell instead of as a script. The shell uses __repr__() to
print objects instead of __str__(), so you either need to use 'print' or
you need to call str(), note the following:
Python 2.7.2+ (default, Oct 4 2011, 20:06:09)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> suits = ['spades', 'clubs', 'diamonds', 'hearts']
>>> ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J',
'Q', 'K']
>>> class Card:
... def __init__(self, rank, suit):
... self.suit = suit
... self.rank = rank
... def __str__(self):
... return suits[self.suit] + ' ' + ranks[self.rank]
...
>>> Card(2, 3) #1
<__main__.Card instance at 0x7f719c3a20e0>
>>> str(Card(2, 3)) #2 of your
'hearts 3'
>>> print Card(2, 3) #3
hearts 3
In #1, the output is the __repr__() of your Card class; you can modify
this output by overriding the __repr__() on your Card class.
In #2, the output is the __repr__() of a string, the string is the
return value from __str__() of your Card class. The repr of a string is
the string enclosed in quotes, which is why there is an extra pair of
quotes.
In #3, you're 'print'-ing a string, the string is the return value from
__str__() of your Card class. There's no extra quotes, since 'print'
prints the string itself, not the repr of the string.
More information about the Python-list
mailing list