SharmaLlama / ticktack

An open-source carbon box model implementation built on JAX.
https://sharmallama.github.io/ticktack
MIT License
11 stars 3 forks source link

Constructor structure. #50

Open Jordan-Dennis opened 1 year ago

Jordan-Dennis commented 1 year ago

Hi all, I've had some more interesting thoughts on the design. One of the more fruity ideas I had was to do with the constructors. Unfortunately, and I have definitely said this before :laughing:, python does not support overloading. I will spare you the details, but the result is that functions, and in particular constructors, can become clogged with logic. Our scenario is not particularly troublesome, but I've concocted an interesting method for implementing multiple constructors that I thought I would share.

class CarbonBoxModel(object):
  boxes: list
  transfer_matrix: array
  def __init__(self, boxes, transfer_matrix):
    self.boxes = boxes
    self.transfer_matrix = transfer_matrix
  @classmethod
  def init_from_file(cls, file_name):
    boxes, transfer_matrix = read_matrix_from_file(file_name)
    return cls(boxes, transfer_matrix)
  @classmethod
  def init_from_name(cls, name):
    file_name = name_to_file(name)
    return cls.init_from_file(file_name)

Correct use of this class is:

cbm = CarbonBoxModel.init_from_name('Guttler14')
cbm = CarbonBoxModel.init_from_file('my/custom/save.hdf')

I think this is pretty cool, but I am curious what other people think.