Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #16655 > unrolled thread
| Started by | Lie Ryan <lie.1296@gmail.com> |
|---|---|
| First post | 2011-12-05 23:41 +1100 |
| Last post | 2011-12-05 23:41 +1100 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Fwd: class print method... Lie Ryan <lie.1296@gmail.com> - 2011-12-05 23:41 +1100
| From | Lie Ryan <lie.1296@gmail.com> |
|---|---|
| Date | 2011-12-05 23:41 +1100 |
| Subject | Re: Fwd: class print method... |
| Message-ID | <mailman.3299.1323088902.27778.python-list@python.org> |
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@davea.name <mailto:d@davea.name>" <d@davea.name > <mailto:d@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.
Back to top | Article view | comp.lang.python
csiph-web