Added hook method to utils so that we can hook new methods dynamically into the classes.

This commit is contained in:
Rowan Cockett
2013-11-22 10:51:01 -08:00
parent dbaea1fda9
commit 6216ae977e
2 changed files with 14 additions and 4 deletions
-1
View File
@@ -118,7 +118,6 @@ class BaseInversion(object):
Where the * can be any string. If present, _doEndIteration* will be called at the start of the default doEndIteration call.
You may also completely overwrite this function.
:param numpy.ndarray xt: tested new iterate that ensures a descent direction.
:rtype: None
:return: None
"""
+14 -3
View File
@@ -12,6 +12,10 @@ import Solver
from Solver import Solver
import Geophysics
import types
import time
import numpy as np
def setKwargs(obj, **kwargs):
"""Sets key word arguments (kwargs) that are present in the object, throw an error if they don't exist."""
for attr in kwargs:
@@ -66,10 +70,17 @@ def callHooks(obj, match, *args, **kwargs):
if getattr(obj,'debug',False): print (match+' is calling self.'+method)
getattr(obj,method)(*args, **kwargs)
def hook(obj, method, name=None, overwrite=False):
"""
This dynamically binds a method to the instance of the class.
import time
import numpy as np
If name is None, the name of the method is used.
"""
if name is None: name = method.__name__
if not hasattr(obj,name) or overwrite:
setattr(obj, name, types.MethodType( method, obj ))
else:
print 'Method '+name+' was not overwritten.'
class Counter(object):