inner classes in python as inner classes in Java
Carlo v. Dango
oest at soetu.eu
Sat Oct 18 17:05:59 EDT 2003
On Thu, 16 Oct 2003 08:30:06 +0000 (UTC), Duncan Booth
<duncan at NOSPAMrcp.co.uk> wrote:
> "Carlo v. Dango" <oest at soetu.eu> wrote in
> news:oprw4lztsdmyya52 at news.kadnet.dom:
>
>>> You'll have to decide what semantics you want to obtain when an
>>> attribute is set on an instance of the "inner class" -- I sure can't
>>> do it on your behalf.
>>
>> 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 the statement in some method in the inner class "self.i =
>> 42" can be interpreted as "create i in the inner class instance" or
>> "lookup i in the 'outer scope' and set it"
>
> What you want wouldn't necessarily be impossible. You should be able to
> create a metaclass for the inner class that automatically creates
> properties in the inner class which access the outer class fields. That
> way
> you could expand:
>
> self.a = 42
>
> to something equivalent to:
>
> self.__outer.a = 42
>
> Actually, thinking about it you need to put the metaclass on the outer
> class rather than the inner one. That way when the outer class is
> created,
> you can check its dictionary for any classes it contains and give each of
> those classes the appropriate properties.
that is a nice idea, however, how do I know which fields are defined in
the outer class?? fields can be defined in every method and on runtime..
class A(object):
def foo(self, arg):
if arg == 0:
self.i = 3 # create a 'i'
else
self.j = 4 # create a 'j'
so when the metaclass examines my A class, are both i and j defined in the
class or how?
> I think it ought also to be possible to add a __get__ method to the inner
> class so that accessing the inner class through an instance of the outer
> class returns what would effectively be a 'bound class' (cf bound method)
> which sets the __outer member automatically when you create an instance
> of
> the inner class.
that would be rather cool, but Im not sure I fully understand your idea.
could you produce some (pseudo) code?
-carlo
--
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/
More information about the Python-list
mailing list