-1
"this is my string".myfunction(argument)

This is very simple in javascript. With the keyword this i can access to my string directly. Is that possible with python?

Enzo
  • 4,111
  • 4
  • 21
  • 33

1 Answers1

1

You can inherit from str and define your own methods:

class myString(str):
    def my_method(self, ...):
        # ...

some_string = myString("StackOverflow")

print some_string.count("a") # method from string
print some_string.myMethod(...) # your defined method
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
  • But i wouldn't like to declare each string as instance of a class. Does not exists more ways to do this? – Enzo Mar 04 '14 at 03:43
  • Maybe you can just create a function that receives two parameters: `my_funcion(str1, str2)` It will be "similar" to `str1.my_function(str2)` – Christian Tapia Mar 04 '14 at 03:46
  • Yeah i think that is the only way to do it. But i wanted to extend the function join. Something like ",".join_reverse(list) but is not possible with this language. – Enzo Mar 04 '14 at 04:06
  • You can always use `join()` in the new function you will create. I don't see the point of "extending" it. – Christian Tapia Mar 04 '14 at 04:07
  • Can i do this: `"my spliter".join_reverse(list)` instead of `join_reverse("my spliter", list)` ? – Enzo Mar 04 '14 at 04:36
  • @EnZo What's the benefit of doing that? It will work anyway. – Christian Tapia Mar 04 '14 at 04:36
  • homogeneity? flexibility? – Enzo Mar 04 '14 at 04:37
  • Sometimes you have to sacrifice those things in order to achieve the *most important*, in this case the operation `join_reverse()`. – Christian Tapia Mar 04 '14 at 04:40
  • What do you mean with "in order to achieve the most important"? – Enzo Mar 04 '14 at 04:44
  • The main goal is to make the operation of `join_reverse()`. In order to do that, you may have to sacrifice flexibility. – Christian Tapia Mar 04 '14 at 05:24
  • Right, but for me is not the only goal. For me is important write a good code, uniform and legible. That's why javascript is my favorite language at this moment. Because give me more flexibility than any other. – Enzo Mar 04 '14 at 07:04
  • How is `join_reverse(str1, str2)` not a good code? Come on. – Christian Tapia Mar 04 '14 at 07:04
  • Could be, but this solution is more elegant `"string".join_reverse(list)` because the original way is `"string".join(list)` is more understandable and consistent. Also other option than give me javascript than python not, is extend the prototype. And i can do something like this: `"string".join(list, reverse)` Reverse is false as default. Anyway, i am learning python and i was wondering if can do some things. Thank you for your help. – Enzo Mar 04 '14 at 08:08