[Tutor] Inheriting from parent object
singletoned at gmail.com
Tue Nov 22 13:41:11 CET 2005
Thanks for this. I hadn't really considered that I would have to
explicitly store parent/child relationships.
Having been browsing for something else, I came across this page about
Unifying types and classes:
>From it, it looks like I could do something like:
def __init__(self, parent):
self.__header = None
self.parent = parent
if not self._header and self.parent:
def setheader(self, header):
self.__header = header
header = property(getheader, setheader)
Which I think would end up doing exactly what I want.
I still don't think I'm clear on the use of self though. Can I only
use it in class definitions?
I think it might be that
myPage = Page(parentPage)
is highly deceptive. Shouldn't it really be:
new Page(myPage, parentPage)
myPage = new Page(myPage, parentPage)
or am I getting really, really confused?
On 15/11/05, alan.gauld at freenet.co.uk <alan.gauld at freenet.co.uk> wrote:
> >>Sorry, I didn't really explain myself clearly.
> Thats OK its easy to get buried in the depths and
> forget everyone else is coming at it cold. But
> the use of non standard terms confused things
> even more!
> >>I want to create a kind of website ...
> >>I want to have a root object, which
> >>has page objects. The page objects
> > will have various properties
> >like header, footer, body and an order
> Sounds like a job for classes. Create a
> Page class with the various properties.
> Initialise objects with their parent
> (ie containing) object.
> >>to inherit the attribute from their parent page (ie if it is
> >>root.chapter3.page5 then chapter3 is the parent of page5).
> >>I guess the psuedo code would be:
> >>def inherit()
> >> return this.parent.attribute
> Just put code like this in the init method:
> Class Page:
> def __init__(self, parent = None):
> self.parent = parent # and handle default too!
> def getHeader(self):
> return self.parent.header
> Then create
> Chapter3 = Page()
> Chapter3.header = '''<h1>some long string here....'''
> p2 = Page(Chapter3)
> p2.getHeader() # returns Chapter3.header
> >>(I know Python doesn't really have a 'this'
> But it does have self.... and you can use
> this if you prefer!
> >>knowing who the function was called by).
> Thats not really needed if you use objects.
> Although self does point at the specific
> Page whose method is being invoked.
> Alan G
More information about the Tutor