[Tutor] constructing objects with one set of required options
Gregory, Matthew
matt.gregory at oregonstate.edu
Fri Sep 17 00:35:37 CEST 2010
Hi James,
James Mills wrote:
> Rather than present you with what I think (subjective)
> might be a "good solution", why don't you look up in the
> python documentation how you define methods and
> what you can do with them (parameters-wise).
>
> I'll summarize:
>
> def foo(self, a, b, c):
> ...
> def foor(self, a, b, *args):
> ...
> def foo(self, a, b, c=None):
> ...
> def foo(self, a, b, *args, **kwargs):
> ...
>
> There are probably other combinations, but these are
> probably the most common.
>
> The point I'm trying to make here is that this is
> really "up to you".
>
> Use a combination of variable arguments (*args)
> and maybe some arguments with default values
> (c=None) or just use **kwargs. Choice is yours :)
Thanks for your reply. I do understand all the different ways parameters can be passed and realize that it's up to me to choose that signature. But, mostly, I wanted advice on how to make this signature as intuitive as possible to a user. So, from my earlier example, a signature with positional args like this is a bad idea:
class Envelope:
def __init__(x_min, y_max, cell_size, *args):
...
# are args 3 and 4 rows and columns or x_max, y_min?
e = Envelope(10, 20, 1, 30, 10)
so I know at least the last two args should probably be keywords, but a signature like this is somewhat confusing to me as well because it's not immediately clear to me what the first three parameters are by looking at the *call* (obviously by looking at the method you can figure it out).
def __init__(x_min, y_max, cell_size, **kwargs):
e = Envelope(10, 20, 1, n_cols=30, n_rows=10)
e = Envelope(10, 20, 1, x_max=30, y_min=10)
So I know I'm getting around to answering my own question, but the clearest way to me was to provide all keyword args. I just didn't know if this was too verbose from a user's standpoint. Really just a stylistic question that might be best left to the individual.
thanks for help,
matt
More information about the Tutor
mailing list