[Tutor] constructing objects with one set of required options

James Mills prologic at shortcircuit.net.au
Fri Sep 17 00:44:02 CEST 2010


On Fri, Sep 17, 2010 at 8:35 AM, Gregory, Matthew
<matt.gregory at oregonstate.edu> wrote:
> 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)

Don't forget "self".

This signature seems okay to me.

> 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.

In my experience, I've always defined explicit arguments and keyword arguments
for constructors and use **kwargs for anything that can be specified as optional
but have defaults. eg:

class Foo(object)
   def __init__(self, a, b, c, x=1, **kwargs):
      super(Foo, self).__init__()

      self.a = a
      self.b = b
      self.c = c

      self.x = x

      self.y = kwargs.get("y", None)

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"


More information about the Tutor mailing list