different ways to strip strings
Kent Johnson
kent at kentsjohnson.com
Mon Feb 27 14:43:47 EST 2006
rtilley wrote:
> s = ' qazwsx '
>
> # How are these different?
> print s.strip()
> print str.strip(s)
They are equivalent ways of calling the same method of a str object.
>
> Do string objects all have the attribute strip()? If so, why is
> str.strip() needed? Really, I'm just curious... there's a lot don't
> fully understand :)
Actually strip is an attibute of the str class. This is generally true -
methods are class attributes.
When you look up an attribute on an instance, if the instance does not
have the attribute, it is looked up on the class. In the case of
methods, there is some magic that converts the attribute to a 'bound
method' - an object that wraps the method and the instance. When you
call the bound method, the actual method is passed the instance (as the
self parameter) plus whatever other arguments you have given it.
For example, here is a simple class with a single method:
>>> class spam(object):
... def ham(self, eggs):
... print eggs
...
Here is a normal method call:
>>> s=spam()
>>> s.ham('Ha!')
Ha!
What may not be immediately apparent is that s.ham('Ha!') is two
separate operations. First is the attribute lookup of s.ham, which
returns the bound method:
>>> s.ham
<bound method spam.ham of <__main__.spam object at 0x00A36D50>>
Second is the actual call of the bound method, which forwards to the
function defined in the class definition:
>>> f = s.ham
>>> f('Ha!')
Ha!
But that's only half the story. Since ham is a class attribute, it can
be looked up on the class directly. Since there is no instance
associated with the lookup, the result is an 'unbound method' object:
>>> spam.ham
<unbound method spam.ham>
To call this method, you have to provide the instance as the first argument:
>>> f=spam.ham
>>> f(s, 'Ha!')
Ha!
So...
s.strip() gets a bound method object from the class and calls it with no
additional argument.
str.strip(s) gets an unbound method object from the class and calls it,
passing a class instance as the first argument.
Kent
More information about the Python-list
mailing list