|
From: Mats W. <ma...@la...> - 2002-02-05 15:00:02
|
At 03:03 PM 2/4/2002 +0100, Jan Wender wrote:
>On Fri, Feb 01, 2002 at 11:35:23PM -0500, Niranjan V. wrote:
>> I am defining a class within another class. The code is
>>
>> class OuterClass:
>> class InnerClass:
>> def __init__(self): >> #Trying to print the
OuterClass 'Name' instance variable
>> #But i am getting NameError
>> print OuterClass.name
>Well, one problem I see here: Name and age are attributes of the instance
from
>the OuterClass. In InnerClass you ask the *class* for the attribute,
while only
>the instance has it.
>I don't think there is an easy way to get there. At first I thought nested
>scopes would help, but I didn't see how you get hold of the OuterClass
>instancesattributes in the InnerClass.
Jython "inner classes" don't work the same way as in Java.
In Python, a class is a class; when you define a class
inside another class definition you've only affected the
visibility of the name bound to the class object.
If you want the InnerClass constructor to have access to
an instance of OuterClass, you have to pass it in - or
as the oft-quoted rule of Python goes: "explicit is better
than implicit".
Try this:
# Inner class definition
class InnerClass:
# inner class constructor
def __init__(self, other):
print other.name
# outer class constructor
def __init__(self):
self.name="outerclass"
self.__age=23
def __printAge__(self):
print self.__age
ic = self.InnerClass(self) # pass instance
if __name__=='__main__':
oc = OuterClass()
oc.__printAge__()
|