473,385 Members | 1,486 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

str and __setitem__

Hi,

What do I need to do to make the code below work as expected:

class str2(str):

def __setitem__(self, i, y):
assert type(y) is str
assert type(i) is int
assert i < len(self)

self = self[:i] + y + self[1+i:]
a = str2('123')
a[1] = '1'
print a
123
The print statement should return 113

Regards tores
Jan 25 '07 #1
3 1683
Tor Erik Soenvisen wrote:
What do I need to do to make the code below work as expected:

class str2(str):

********def __setitem__(self, i, y):
****************assert type(y) is str
****************assert type(i) is int
****************assert i < len(self)

****************self = self[:i] + y + self[1+i:]
'self' is a local variable; assigning to it rebinds it but has no effect
outside of the __setitem__() method.
a = str2('123')
a[1] = '1'
print a
123
The print statement should return 113
You have to start from scratch as a strings are "immutable" (once created,
their value cannot be changed).
>>class mutable_str(object):
.... def __init__(self, value):
.... self._value = value
.... def __setitem__(self, index, value):
.... self._value = self._value[:index] + value +
self._value[index+1:]
.... def __str__(self):
.... return self._value
....
>>a = mutable_str("123")
a[1] = "x"
print a
1x3

Peter
Jan 25 '07 #2
On Thu, 25 Jan 2007 10:16:31 +0000, Tor Erik Soenvisen wrote:
Hi,

What do I need to do to make the code below work as expected:
Use another language *wink*

Python strings are immutable, you can't change them in place.
class str2(str):

def __setitem__(self, i, y):
assert type(y) is str
assert type(i) is int
assert i < len(self)
self = self[:i] + y + self[1+i:]
This line rebinds a NEW string to the name "self" -- it doesn't change the
contents of the original string. Because the name self is local to the
method, it doesn't change references to the original string.

Are you sure you need mutable strings?

Here are a few different ways of getting something like a mutable string:

* use the MutableString class from the UserString module;

* use the mmap module;

* use lists of characters instead of strings;
--
Steven

Jan 25 '07 #3
Peter Otten:
>class mutable_str(object):... def __init__(self, value):
... self._value = value
... def __setitem__(self, index, value):
... self._value = self._value[:index] + value +
self._value[index+1:]
... def __str__(self):
... return self._value
...>>a = mutable_str("123")
>a[1] = "x"
print a
For this purpose an array may be better, if you have to change it often
and print is only once in a while:

from array import array
a = array("c", "123")
a[1] = "x"
print a

The OP can also use a class, if some other methods are needed:

from array import array

class mutable_str(object):
def __init__(self, value):
self._value = array("c", value)
def __setitem__(self, index, value):
self._value[index] = value
def __str__(self):
return self._value.tostring() # this requires time

a = mutable_str("123")
a[1] = "x"
print a

Probably array.array can be subclassed too...

bye,
bearophile

Jan 25 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Nicodemus | last post by:
Hi all, I found a surprising behavior regarding new-style classes operator lookup. It seems that for operators, the instance methods are ignored. Observe: >>> class C: .... def foo(self):...
3
by: Dave Opstad | last post by:
According to the documentation the __setslice__ method has been deprecated since Python 2.0. However, if I'm deriving classes from the builtin list class, I've discovered I can't really ignore...
9
by: Ron Garret | last post by:
Is this a bug or a feature? class mydict(dict): def __setitem__(self, key, val): print 'foo' dict.__setitem__(self, key, val) >>> d=mydict() >>> d=2 foo
1
by: morphex | last post by:
Hi, I get the following messages running the testall.py script with m2crypto 0.13, can anyone tell me what's wrong? .................................................................EEEEEE...
1
by: Crutcher | last post by:
I've been playing with dictionary subtypes for custom environments, and I encountered a strange interaction between exec, dictionary subtypes, and global variables. I've attached a test program,...
35
by: nagy | last post by:
I do the following. First create lists x,y,z. Then add an element to x using the augumented assignment operator. This causes all the other lists to be changed also. But if I use the assignment...
8
by: Almad | last post by:
Hello, I discovered this behaviour in dictionary which I find confusing. In SneakyLang, I've tried to extend dictionary so it visits another class after something is added: class...
12
by: jeremito | last post by:
Please excuse me if this is obvious to others, but I can't figure it out. I am subclassing dict, but want to prevent direct changing of some key/value pairs. For this I thought I should override...
5
by: Mike Kent | last post by:
For Python 2.5 and new-style classes, what special method is called for mylist = seq and for del mylist (given that mylist is a list, and seq is some sequence)? I'm trying to subclass list, and...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.