translating PHP to Python

Peter Hansen peter at engcorp.com
Sun Feb 5 15:04:32 EST 2006


Dave wrote:
> The second point won't work, though, because by parent class I mean,
> simply, the object that created the current object, *not* the class the
> current class is based on.

Good you clarified that, because "parent" definitely isn't used that way 
by most other people here.  And, in fact, there's no requirement that an 
instance (object) be involved in creating a new object.  Python allows 
functions that are not methods in a class.  What would you expect to 
happen if a mere function was doing the creating?

> So, for example:
> 
> class A(object):
>     def __init__(self):
>         self.thing = Thing()
>         self.thing.meth()
> 
>     def do_stuff(self):
>         print "Stuff"
> 
> class Thing(object):
>     def meth(self):
>         #now here's what I WANT
>         self.parent.do_stuff(args)
> 
> Is there a built in way to do this in Python, or do I have to pass
> "parent" when I init Thing?

It's pretty much standard to pass in references to the caller, or 
perhaps even more standard to pass in a callable, often in the form of a 
a "bound method" when an object's method is doing the calling.  On the 
other hand, what you are showing here is something that *would* normally 
be done with subclassing, and therefore with a parent class involved 
(using the conventional meaning of "parent").

class A(object):
     def __init__(self):
         self.do_stuff()


class Thing(A):
     def do_stuff(self):
         print "Stuff"


But since this was a contrived example, I can't really tell what would 
work best for you in your real use case.

-Peter




More information about the Python-list mailing list