str class inheritance prob?

Jerry Hill malaclypse2 at gmail.com
Wed Apr 16 15:18:15 EDT 2008


On Wed, Apr 16, 2008 at 2:35 PM, Hamish McKenzie
<hamish at valvesoftware.com> wrote:
> so I'm trying to create a class that inherits from str, but I want to run
> some code on the value on object init.  this is what I have:

You actually want to run your code when creating the new object, not
when initializing it.  In python, those are two separate steps.
Creation of an instance is handled by the class's __new__ method, and
initialization is handled by __init__.  This makes a big difference
when you inherit from an immutable type like str.

Try something like this instead:

class Path(str):
    def __new__( cls, path ):
        clean = str(path).replace('\\','/')
        while clean.find('//') != -1:
            clean = clean.replace('//','/')
        print 'cleaned on __new__:\t',clean
        return str.__new__(cls, clean)


-- 
Jerry



More information about the Python-list mailing list