Reputation: 23
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
Reputation: 2484
Note that in Python you could just use the multiplication operator on string:
>>> s = "foo"
>>> s*2
'foofoo'
Upvotes: 0
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:
CamelCaseCapitalization
so people can recognize they are classes. str
and some other builtins don't follow this, but everyone's user-defined classes do.__new__
. Defining __init__
will probably work. They way you've defined __new__
isn't especially helpful.Upvotes: 2
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