How to automate accessor definition?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Mar 20 22:31:32 EDT 2010


On Sat, 20 Mar 2010 22:15:54 +0000, kj wrote:

> I need to create a class solely for the purpose of encapsulating a large
> number of disparate data items.

There's a built-in for that. It's called "dict". Syntax for item access 
is a tiny bit different, but still very common:

data['foo']

instead of

data.foo

If you need to customize item access, you need to modify __getitem__, 
__setitem__ and __delitem__ instead of __getattr__ etc., but otherwise 
they are nearly identical. Ignoring a few complications due to slots and 
inheritance, attribute access is built on top of item access, so you 
won't notice any performance hit (and you might see a tiny performance 
benefit).


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

Huh? If you have instance variables, why don't you refer to them by name?

x = MyClass()  # create an instance
y = MyClass()  # another variable bound to an instance
z = MyClass()  # etc.
print x, y, z



> (In case it matters, this class
> is meant to be a private helper class internal to a module, and it won't
> be subclassed.)
> 
> What is "best practice" for implementing this sort of class *succinctly*
> (i.e. without a lot of repetitive accessor code)?

Leave the repetitive accessor code out. Python isn't Java.

http://dirtsimple.org/2004/12/python-is-not-java.html


> 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

Classes already support that.


>>> class C(object):
...     pass
...
>>> i = C()
>>> i.field = 42
>>> val = i.field
>>> i.field += 6
>>> print (val, i.field)
42 48


 
> ...rather than this one
> 
>   val = i.get_field()
>   i.set_field(i.get_field() + 6)
> 
> ?

Good grief! No wonder Java coders are so unproductive :(




-- 
Steven



More information about the Python-list mailing list