tomS
tomS

Reputation: 33

Class method that alters the object

I've been learning about classes in python and I was trying to write a reverse method for an extended string class, which looks like:

class NewString(str):
    
    def reverse(self):
        self = self[::-1]

string = NewString('Python')
string.reverse()
print(string)

I expected it to print 'nohtyP' but it doesn't. It keeps the original value of the string and prints 'Python'. Can anyone explain to me why this doesn't work and how I could change the class to get it to do what I expected. There is no purpose for this other than learning more about how classes work.

Upvotes: 3

Views: 201

Answers (1)

user2390182
user2390182

Reputation: 73450

self is just a local variable in the method. Reassigning it won't mutate the object it referred to before. Since strings are immutable, so are objects of your string subclass. All you can do is return new string objects from the methods:

class NewString(str):
    def reverse(self):
        return self.__class__(self[::-1])  # casts to the specific type of self

string = NewString('Python')
rev = string.reverse()
print(rev)
# nohtyP
type(rev)
# NewString

Upvotes: 3

Related Questions