From 6216ae977ef52d74a460c0551bf46f8a42b1b060 Mon Sep 17 00:00:00 2001 From: Rowan Cockett Date: Fri, 22 Nov 2013 10:51:01 -0800 Subject: [PATCH] Added hook method to utils so that we can hook new methods dynamically into the classes. --- SimPEG/inverse/Inversion.py | 1 - SimPEG/utils/__init__.py | 17 ++++++++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/SimPEG/inverse/Inversion.py b/SimPEG/inverse/Inversion.py index 254e7651..a8e05a1a 100644 --- a/SimPEG/inverse/Inversion.py +++ b/SimPEG/inverse/Inversion.py @@ -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 """ diff --git a/SimPEG/utils/__init__.py b/SimPEG/utils/__init__.py index f7daf273..724f6f38 100644 --- a/SimPEG/utils/__init__.py +++ b/SimPEG/utils/__init__.py @@ -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):