tags:

views:

66

answers:

3

I want to define a new class that inherit the build in str type, and create a method that duplicates the string contents.

How do I get access to the string value assigned to the object of my new class ?

    class str_usr(str):
        def __new__(cls, arg):
            return str.__new__(cls, arg)
        def dub(self):
            # How to modify the string value in self ?
            self.<attr> = self.<attr> + self.<attr>

Thanks for any help :-)

+2  A: 

It doesn't look like you want to inherit from str at all (which is prettymuch never useful anyhow). Make a new class and have one of its attributes be a string you access, that is

class MyString(object):
    def __init__(self, string):
        self.string = string

    def dup(self):
        self.string *= 2

Also, note about this:

  • Name your classes with CamelCaseCapitalization so people can recognize they are classes. str and some other builtins don't follow this, but everyone's user-defined classes do.
  • You don't usually need to define __new__. Defining __init__ will probably work. They way you've defined __new__ isn't especially helpful.
  • To add new functionality to strings, you probably don't want a class; you probably just want to define functions that take strings.
Mike Graham
Thanks for the thorough answer.
MZ_DK
+1  A: 

Strings in Python are immutable, so once you have one string, you can't change its value. It's almost the same as if you had a class derived from int, and then you added a method to change the value of the int.

You can of course return a new value:

class str_usr(str):
    def dup(self):
        return self + self # or 2 * self

s = str_usr("hi")
print s # prints hi
print s.dup() # print hihi
Alok
Thanks, that answered my question. However, from both your and Mike Grahams answer, I can see that my idea was not a good general approach.
MZ_DK
A: 

Note that in Python you could just use the multiplication operator on string:

>>> s = "foo"
>>> s*2
'foofoo'
paprika
Ah, I just see that Alok already mentioned this... Well, I'll leave my answer anyway to emphasize that subclassing in this case is overengineering/obfuscation.
paprika
Your answer is good because it mentions that the OP doesn't probably need subclassing. We don't know what he wants to do with his subclass, though.
Alok