How to automate accessor definition?
Chris Rebert
clp2 at rebertia.com
Sat Mar 20 18:54:20 EDT 2010
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
More information about the Python-list
mailing list