inner classes in python as inner classes in Java

Alex Martelli aleaxit at yahoo.com
Wed Oct 15 18:20:44 EDT 2003


Carlo v. Dango wrote:

> Comming to think of it, it can't be done in python! Since there is no way
> to denote you want to access a field rather than creating a new one,

When you access a field you access it, e.g:

    print blah.bluh

this accesses it -- it will never create anything.  When you ASSIGN to a 
field you create it if it wasn't there (if it was there, the previous value 
is removed, and the field is created afresh again).  You can use
descriptors (in new-style classes) to handle assignments (and accesses
too, if you want) in special ways for some attributes.


> __setattr__ will have no changes of knowing when to create the field or
> look it up in the outer scope... this suxx man... I never understood the
> smart thing about that feature in python.. anyone care to enlighten me?

If you can't see that it's simpler to let

   target = value

have the same semantics whether target was already bound to something
or not, it's hard to see what will convince you.

For the case of someobject.attr = value, you do get to add complications
if you want -- e.g., when wrapping someobject in your proxy, you can
introspect to find what attributes it had at that time, and prepare a
custom class with the set of descriptors you want.  Or, if you are in no
hurry, you can to such checks at the time of eahc assignment.

Such tender loving care will typically break the semantics of your
proxying in general cases, but if you have total control on the class
whose instances you're wrapping that need not be the case.  It's
still hard to say what benefits you'll be getting, of course, but there
may be some cunning plan behind it all.


Alex





More information about the Python-list mailing list