inner classes in python as inner classes in Java
Daniel Dittmar
daniel.dittmar at sap.com
Thu Oct 16 11:43:50 EDT 2003
> Carlo v. Dango wrote:
>> I want the semantics of java's inner classes and the semantics of
>> inner methods... that the inner class shares the fields and methods
>> of its outer class instance.. But I've come to realize I can't do
>> this in python, as
Alex Martelli wrote:
> I don't understand what you mean. "inner methods" (? presumably you
> mean nested functions ?) cannot re-bind names in outer scope -- you
> say you want these semantics, and you also seem to say you DO want
> assignments on the innerobject's attribute to re-bind attributes on
> the outer. There is a contradiction here in what you say. Neither
> in Python nor with any other tools whatsoever can you implement
> contradictory requirements.
Inner classes (not static inner classes) in Java work as follows:
- the inner class has a reference to an object of the enclosing class
- any identifier is searched in the method scope, the inner class scope, the
enclosing class scope, so an identifier A can mean A (local), this.A
(inner), this.__enclosing__.A (enclosing), depending on where the compiler
finds it.
A Python implementation for inner classes would be:
class Inner:
def __init__ (self, enclosing):
self.__enclosing__ = enclosing
def __getattr__ (self, name):
return getattr (self.__enclosing__, name)
def __setattr__ (self, name, value):
if hasattr (self.__enclosing__):
setattr (self.__enclosing__, name, value)
else:
setattr (self, name, value)
Java hides the 'enclosing' when creating objects, so
new Inner ()
becomes
new Inner (this)
Not that I think that hiding the real access path is a good idea.
Daniel
More information about the Python-list
mailing list