Using Unbound Methods In Another Python Class
Solution 1:
If you want to add the same method to several unrelated classes (e.g. doing AOP), don't copy an unbound method from one of them. Instead, define a plain function and assign it as a method to every class.
Usually a better way to do it is a mixin (using plain inheritance) or a metaclass (class decorator syntax is neat).
If you're hell-bound to steal a method from a class (e.g. one you don't control), you can extract it from the 'unbound method' wrapper: foo2.ops.im_func
; it's a plain function and you can assign it as a method to another class.
Solution 2:
If you want to implement 'class methods', you should call it accordingly, whithout object instance
classfoo:
@staticmethoddefops(name):
print"Hi there",name
foo.ops("Peter")
classfoo2:
pass
foo2.ops = staticmethod(foo.ops)
foo2.ops('aa')
(copy-pasted from http://code.activestate.com/recipes/52304-static-methods-aka-class-methods-in-python/)
if you want instance method, use inheritance
Post a Comment for "Using Unbound Methods In Another Python Class"