MZ_DK
MZ_DK

Reputation: 23

How to access string value from new class that inherit string type

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 :-)

Upvotes: 2

Views: 1272

Answers (3)

paprika
paprika

Reputation: 2484

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

>>> s = "foo"
>>> s*2
'foofoo'

Upvotes: 0

Mike Graham
Mike Graham

Reputation: 76773

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.

Upvotes: 2

Alok Singhal
Alok Singhal

Reputation: 96211

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

Upvotes: 4

Related Questions