0

Python allows for methods to be add to instances of a class rather than the whole class as demonstrated her Adding a Method to an Existing Object Instance. Most of the time this seems like a bad idea for consistent behavior of classes. When might this be necessary? Why does python allow this at all?

Francis
  • 23
  • 4

1 Answers1

1

Python doesn't specifically allow this, it's just a consequence of the way the Python object model works. Methods are just object attributes like any other; and generally you can add any attribute to an existing object.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • ahh. So this feature was not included for a purpose but rather is a side effect of the implementation of python as a language? (and there for I should not do this....?) – Francis Apr 19 '18 at 17:27
  • Feel free to do it. There are certainly cases when it is useful, for example monkey-patching and especially mocking in tests. – Daniel Roseman Apr 19 '18 at 17:29
  • 1
    @Francis it's a consequence of the object model, not really the implementation. Generally, Python sticks to the notion that "we are all consenting adults", and doesn't protect you from doing silly things. I sometimes do it when I'm trying to debug / write a method in a REPL, but never in production code. Perhaps there are valid use-cases in mocking/testing, but other than that, I don't encounter them. – juanpa.arrivillaga Apr 19 '18 at 17:29
  • 1
    @Francis - I wouldn't express it that way. The creator of Python was surely aware of the consequences of whatever object model he chose. Therefore, if he had felt it was "sufficiently important" to *prevent* different instances of the same class from having different methods, then he would have chosen an object model accordingly. What I am saying is, he might not have had any specific use case in mind, but he also clearly didn't want to close that door. The resulting behavior is not a "side effect". There is certainly nothing accidental or unintended about it. – John Y Apr 19 '18 at 17:35
  • Thanks for the clarification. So its more of a laiz fair, "use at your own risk" model – Francis Apr 19 '18 at 17:52