Sheena
Sheena

Reputation: 16212

extending a python class by adding more methods post definition

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?

Upvotes: 0

Views: 45

Answers (1)

ecatmur
ecatmur

Reputation: 157334

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.

Upvotes: 1

Related Questions