How to automate accessor definition?

Someone Something fordhaivat at gmail.com
Sun Mar 21 01:53:45 CET 2010


Just initialize everything in the constructor, unless you have *really *good
reason not to do that.
On Sat, Mar 20, 2010 at 6:54 PM, Chris Rebert <clp2 at rebertia.com> wrote:

> On Sat, Mar 20, 2010 at 3:15 PM, kj <no.email at please.post> wrote:
> > I need to create a class solely for the purpose of encapsulating
> > a large number of disparate data items.  At the moment I have no
> > plans for any methods for this class other than the bazillion
> > accessors required to access these various instance variables.
> > (In case it matters, this class is meant to be a private helper
> > class internal to a module, and it won't be subclassed.)
>
> If it's just a completely dumb struct-like class, you might consider
> something like:
> http://docs.python.org/library/collections.html#collections.namedtuple
>
> > What is "best practice" for implementing this sort of class
> > *succinctly* (i.e. without a lot of repetitive accessor code)?
>
> Is there any good reason you can't just use straight instance
> variables? Python ain't Java; vanilla, boilerplate accessor methods
> should almost always be avoided.
>
> > Also, one more question concerning syntax.  Suppose that i represents
> > an instance of this class.  Is it possible to define the class to
> > support this syntax
> >
> >  val = i.field
> >  i.field += 6
> >
> > ...rather than this one
> >
> >  val = i.get_field()
> >  i.set_field(i.get_field() + 6)
> >
> > ?
>
> Yes, using the magic of the property() function:
> http://docs.python.org/library/functions.html#property
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100320/9c839ac7/attachment.html>


More information about the Python-list mailing list