Search code examples
pythonstringclassextend

Extend str class to take additional parameters


I want to create a new class that is a special type of string. I want it to inherit all the methods of the str class, but I want to be able to pass it an additional parameter that it can use. Something like this:

class URIString(str, ns = namespace): # ns defaults to global variable namespace
    def getLocalName(self):
        return self[(self.find(ns)+len(ns)):] # self should still act like a string
        # return everything in the string after the namespace

I know the syntax isn't right. But hopefully it conveys the idea that I'm trying to get at.


Solution

  • You would want to do something like this:

    class URIString(str):
        _default_namespace = "default"
    
        def __init__(self, value, namespace=_default_namespace):
            self.namespace = namespace
    
        def __new__(cls, value, namespace=_default_namespace):
            return super().__new__(cls, value)      
    
        @property
        def local_name(self):
            return self[(self.find(self.namespace)+len(self.namespace)):]
    

    I have used the @property decorator to turn getLocalName() into the attribute local_name - in python, getters/setters are considered bad practice.

    Note that pre-Python 3.x, you need to use super(URIString, cls).__new__(cls, value).