3

I once stumbled upon this StackOverflow page, when I was learning JavaScript. It taught me how to make a function that can be called by writing something like 35.myFunction(parameter)

Now, I've added Python to my cache of languages, and can't figure out how to accomplish the same thing in python.

To be more precise: I would like to make a python function that can be called with a value and a dot before it.

For example: "Hello World?".replace("?", "!")

If someone could tell me how to make such a function, and give an example, I would greatly appreciate it.

Community
  • 1
  • 1
CJ Goldshine
  • 135
  • 1
  • 2
  • 11
  • 2
    What do you want this "dot function" to accomplish? Do you have specific kinds of values you want to operate on? Do you want to be able to write `.replace(x, y)` after _anything_? – jscs Jul 22 '14 at 00:06
  • "I am reminded of something Wolsey once told me, that I should only ever tell the king what he ought to do, not what he could do; for if the lion knows his own strength, no man could control him." -- Thomas More. Just because you can do something in a language definitely does not mean you *should.* – Michael Lorton Jul 22 '14 at 00:23
  • I don't really care what type of value it operates on. For example's sake, I'd like it to add 2 to an integer. For example: `x = 5` and then `x.myFunction()` makes x equal to 7. – CJ Goldshine Jul 22 '14 at 00:29

1 Answers1

4

You can't do so for arbitrary types, since types defined in C cannot have arbitrary attributes added to them. However:

class C(object):
  pass

def do_something(self):
  print self.__name__

o = C()
C.printname = do_something

o.printname()
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358