[Tutor] Walking up
Don Arnold
Don Arnold" <darnold02@sprynet.com
Tue Nov 26 07:36:48 2002
----- Original Message -----
From: <janos.juhasz@VELUX.com>
To: <tutor@python.org>
Sent: Tuesday, November 26, 2002 5:07 AM
Subject: [Tutor] Walking up
> Hi All,
>
> I have got a simple problem, on getting attributes from the outer domain
of
> an object.
>
> ########
> class child:
> def __init__(self, text):
> self.child_text = text
>
> class parent:
> def __init__(self, text):
> self.parent_text = text
> self.child = child(self.parent_text + ' - child')
>
> myObj = parent('parent')
>
> theChild = myObj.child
> ## How can i get the 'parent_text' attribute from the 'theChild' object ?
>
> How can i place a function into the child object, that use the variables
of
> the parent ?
>
> Best Regards,
> Janos
>
I'm no OO expert, but here's my two cents. Have your Child store a reference
to its Parent in its constructor:
class Child:
def __init__(self, parent, text):
self.my_parent = parent
self.child_text = text
def show_parent_text(self):
print 'my parent has text:', self.my_parent.parent_text
class Parent:
def __init__(self, text):
self.parent_text = text
self.child = Child(self, self.parent_text + ' - child')
myObj = Parent('parent')
theChild = myObj.child
theChild.show_parent_text()
>>>
my parent has text: parent
>>>
This way, a Child can access its Parent's attributes through self.my_parent.
HTH,
Don