losing subclass behavior

Robin Munn rmunn at pobox.com
Thu Feb 20 16:31:31 EST 2003


Ian McMeans <imcmeans at telus.net> wrote:
> I want to subclass string (into a URL type). However, I want to be able to
> use a URL wherever I can use a string. I want the URL to remain a URL, even
> after string operations.
> 
> Right now, I've got a bit of a problem. When I do it like this:
> class URL(string):
>     ... # stuff here
> 
> and then do:
> url = URL("blah")
> url = re.sub('#.*', '', url)
> 
> then url is no longer a URL (it is now a string).

The name "url" is just a name. re.sub returns a string, so url is now a
name that refers to a certain string. If you wanted a URL object made
from what re.sub returns, the easiest and simplest (and IMHO best) way
to do it is simply this:

    url = URL("blah")
    url = URL(re.sub('#.*', '', url))

Note that you're calling the URL.__init__ function every time you do
this, so try to make sure it's not doing anything too computationally
expensive.

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838




More information about the Python-list mailing list