[Tutor] constructing objects with one set of required options
matt.gregory at oregonstate.edu
Thu Sep 16 23:43:30 CEST 2010
Sorry for what is probably a poor subject line ...
Generally, I'm trying to understand the best way to set up an object's __init__ if there are some required parameters and other parameters that can be specified in a number of ways. As an example, I'm working on an envelope class that describes a spatial envelope complete with cell size information. Assuming that this envelope needs to have its upper left corner specified and a cell size, I can *either* specify a lower right corner or the number of rows and columns to finish the specification. Can folks provide guidance on a good way to do this? Specifically, I'm wondering if some or all options should be by position or by keyword.
Here's my first cut of doing it all by keyword.
def __init__(self, **kwargs):
self.x_min = kwargs['x_min']
self.y_max = kwargs['y_max']
self.cell_size = kwargs['cell_size']
err_str = 'Not all required parameters were specified'
# First try n_cols and n_rows as keyword args
self.n_cols = kwargs['n_cols']
self.n_rows = kwargs['n_rows']
# Try x_max and y_min instead
self.x_max = kwargs['x_max']
self.y_min = kwargs['y_min']
err_str = 'Either the number of rows and columns or '
err_str += 'the lower-right coordinate was not specified.'
# calculate the remaining parts of the specification
(I realize that I could also specify the x_max and the n_rows or y_min and n_cols and still derive the envelope, but that seemed nonintuitive to me, although maybe I should consider it.)
thanks for help,
More information about the Tutor