Inner classes
Isaac To
kkto at csis.hku.hk
Wed Jun 13 23:02:21 EDT 2001
>>>>> "Andrew" == Andrew Kuchling <akuchlin at mems-exchange.org> writes:
Andrew> xyzmats at laplaza.org (Mats Wichmann) writes:
>> Nonetheless, I was challenged by someone to describe how it isn't a
>> shorcoming in Python that classes don't work this way and didn't
>> convince the guy so I'm looking for a more erudite comparison.
Andrew> Work *what* way? It's perfectly legal to do this:
Andrew> class C: class inner: ... stuff for inner class ... stuff for
Andrew> class C
No if the original poster wants a Java-style inner class. Java inner class
is a rather strange concept. The idea is for the inner class instance to
have a reference to the outer class, and unlock the namespace of the outer
class in methods of the inner class. It works like this in Python syntax:
class outer:
def __init__(self):
self.d = 2
def f(self):
print self.d
# The following does not exist in Python
class inner:
def __init__(self):
# should already got a hidden reference to an outer instance
self.d2 = 5 # can also have its own data
def g(self):
print self.d # should print the d of outer reference
self.f() # should call f for the outer reference
print self.d2 # print d2 of inner
def h(self): # return instance of inner class
return self.inner()
x=outer() # create instance
y=x.h() # y is an inner instance
y.g() # print 2 twice and then 5
Of course, currently the above says "Attribute Error: x" in the last line.
Regards,
Isaac.
More information about the Python-list
mailing list