Skip to content

Instantly share code, notes, and snippets.

@autocorr
Last active August 29, 2015 14:11
Show Gist options
  • Save autocorr/d9675c2c40ab6a1d4438 to your computer and use it in GitHub Desktop.
Save autocorr/d9675c2c40ab6a1d4438 to your computer and use it in GitHub Desktop.
A factory function
"""
An example of a class and a factory function.
"""
import model_fit # fit_func lives here
class Fitter(object):
# This would be the starting point for your fit routine,
# and the different methods could do different parts. You could
# use hidden methods with an appended underscore to make the
# methods more modular and single purpose.
def __init__(self, xdata, params, covar):
self.xdata = xdata
self.params = params
self.covar = covar
# Everything that the object would be expected to have should
# be in `__init__`, and all instance attributes should be defined
# here as well, otherwise it can be difficult to pin-point
# where they are created.
self.yfit = self.fit(xdata, params)
# Static methods don't need `self` or to access the class instance.
# You might want something like this because it uses the method name
# `fit` to hide or abstract away the implementation details of the
# specific fit routine from `fit_func`. These also can just be
# accessed directly with `Fitter.fit(...)` without actually creating an instance.
@staticmethod
def fit(xdata, params):
return model_fit.fit_func(xdata, *params)
# Here is a factory method that returns a fully initalized version
# of the class with only input parameters. The distinct advantage
# of this is that if you ever make a new Fitter class, as long
# as it takes the same arguments and uses the same method names
# (such as `.fit`), the factory function can stay the same. This is called
# polymorphism in Object Oriented Programming, or in Python commonly
# referred to as Duck Typing (ie walks like a duck, talks... etc.), in
# that objects can be interchangeable as long as they have the same
# arguments and methods.
def fit_factory(xdata, params, covar, FitterClass=Fitter):
fitter = FitterClass(xdata, params, covar)
# If our Fitter class was more complicated we could run
# other methods here too.
# fitter.foo()
# fitter.bar()
# fitter.baz()
return fitter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment