简体   繁体   中英

Python: How to add a custom function to a pre-existing object?

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?

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM