| 06 Mar 2009 09:29:13 pm by Kllrnohj |
|
Quote |
| elfprince13 wrote: |
so you *do* still have to tell it what kind of formatting you want. granted, being able to pass in an object is a cool, but I'm having trouble envisioning a situation where that would be more useful than the old way of doing it. |
Yes, but you don't have to specify the *TYPE* of the object. That is the point. Formatting stays the same regardless of the number's TYPE (indeed, regardless of the object type - classes can handle the format string however they want). The old way requires you to know the type.
Old busted way is basically sprintf - everything breaks if the type is wrong.
And honestly, who wants to remember if they are supposed to use %s or %d or %f or is it %F etc.... Especially in a language like Python where you never care what the type is - right up until you want to print it. I can't tell you how many times I've just done
| Code: |
| print 'blah blah: %s' % str(some_argument) |
because I didn't know what the type would be. |
| 06 Mar 2009 11:17:20 pm by elfprince13 |
|
Quote |
| on that note....the only thing that irks me about python occasionally is that when you print an object or try to concatenate it to a string it doesn't automatically call __str__() on the object. |
| 06 Mar 2009 11:19:07 pm by calc84maniac |
|
Quote |
| It doesn't? O_o That's a new one on me. |
| 07 Mar 2009 02:06:46 am by elfprince13 |
|
Quote |
| calc84maniac wrote: |
| It doesn't? O_o That's a new one on me. |
nope, or at least not always. For example.
| Code: |
>>> print sabacc.players
[<sabacc.SabaccPlayer instance at 0x8e698>, <sabacc.SabaccPlayer instance at 0x8e6c0>, <sabacc.SabaccPlayer instance at 0x8e6e8>, <sabacc.SabaccPlayer instance at 0x8e710>]
>>> print [player.__str__() for player in sabacc.players]
['Name: Bob\tCredits: 189', 'Name: Fred\tCredits: 276', 'Name: Sally\tCredits: 335', 'Name: Harold\tCredits: 350']
>>> print sabacc.players[0]
Name: Bob Credits: 189 |
|
| 07 Mar 2009 04:08:02 am by Kllrnohj |
|
Quote |
| elfprince13 wrote: |
| on that note....the only thing that irks me about python occasionally is that when you print an object or try to concatenate it to a string it doesn't automatically call __str__() on the object. |
Of course it doesn't. It calls repr() on it, which in turn invokes the class's __repr__() method.
| Code: |
>>> class foo:
... def __repr__(self):
... return "see?"
...
>>> class bar:
... def __str__(self):
... return 'heh'
...
>>> foo()
see?
>>> bar()
<__main__.bar object at 0x027C20B0>
>>> print(foo())
see?
>>> print(bar())
heh
>>> |
|