0

Is it possible to add your own custom function to an already existing object?

For example, the 'string' datatype has no built-in reverse() function unlike in a list, is there a way to add a reverse function such that if I have a string variable var, var.reverse() returns the string in reverse?

One way I think this would work is if I create a class CustomString that has the same properties as a string but with an additional defined reverse function, is this possible? (I'm not yet familiar with Python OOP)

Or is there another way of doing this?

kylieCatt
  • 10,672
  • 5
  • 43
  • 51
DarkPotatoKing
  • 499
  • 2
  • 9
  • 17
  • What you're describing is referred to as "monkey patching", but you can't use it on string objects; subclassing is your best option here. – jonrsharpe Oct 26 '14 at 07:59

1 Answers1

0

You could do this using inheritance:

class new_string(str):
    def reverse(self):
        blah

s = new_string('hello')
s.reverse()

EDIT: Does your code look like this:

>>> class S(str):
...     def reverse(self):
...         return self.__str__()[::-1]
... 
>>> s = S('hello')
>>> s.reverse()
'olleh'
kylieCatt
  • 10,672
  • 5
  • 43
  • 51
  • Thanks :) but I have another question, how do I save the changes done? as in [here](http://pastebin.com/Ct9Dd5CZ) – DarkPotatoKing Oct 26 '14 at 08:13
  • nope, it looks like [this](http://pastebin.com/Ct9Dd5CZ) Can you please tell me what's wrong? :) I want `reverse()` to be a process that reverses the string itself instead of returning a copy of the string in reverse. – DarkPotatoKing Oct 26 '14 at 08:43
  • 1
    That should really be opened as a new question – kylieCatt Oct 26 '14 at 08:45
  • Alright, I see, thanks :) Gonna ask this as a new question after the post limit expires. – DarkPotatoKing Oct 26 '14 at 08:48
  • 1
    @DarkPotatoKing Python strings are immutable so I'm not really sure you'll be able to accomplish what you want to. – kylieCatt Oct 26 '14 at 08:55