0
class A:
    pass

def b(self):
    print('b')

A.b = b

a = A()

At this point a.b is a bound method object which is great, but if i say:

a.b() 

I get an error saying that b needs at least one argument.

My questions are: 1. how does one go about tacking methods onto existing classes? and 2. are there any documented 'best practices' with regard to this sort of thing?

1
  • 1
    That exact code works for me. Can you show the details of the error? Commented Jun 18, 2012 at 14:31

1 Answer 1

1

That should work fine (see: http://ideone.com/WWPg8)

Python functions are descriptors, and convert to unbound and bound methods when accessed on classes and instances respectively; see http://docs.python.org/howto/descriptor.html

"Monkey patching" classes and instances is considered perfectly OK, as long as you're clear about what you're doing and document it sufficiently.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help. I think I made a typo in my code somewhere when I was testing that functionality

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.