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.

3
  • 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? Commented Jul 22, 2014 at 0: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. Commented Jul 22, 2014 at 0: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. Commented Jul 22, 2014 at 0:29

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.