calling objects parents' __init__?

U

user

Normally, when I inherit from a class that I have written,
I want instances of the new class to call the __init__ of
the old (actually, starting from the top of the tree, and
moving on down).

What is the preferred way to do this?

Thanks,

Tobiah
 
J

John Roth

Normally, when I inherit from a class that I have written,
I want instances of the new class to call the __init__ of
the old (actually, starting from the top of the tree, and
moving on down).

What is the preferred way to do this?

If you're using a new style class (one that inherits from
object,) look at the super() built in function. Be a bit
cautious with it, the usage isn't exactly obvious.
There's also an article on the method resolution order
somewhere that makes quite interesting reading.

If you're using an old style class, you have to call
them directly: superklas.__init__(self).

John Roth
 
P

Peter Hansen

Normally, when I inherit from a class that I have written,
I want instances of the new class to call the __init__ of
the old (actually, starting from the top of the tree, and
moving on down).

What is the preferred way to do this?

The preferred way is to call your parent's __init__, if it
has one:

class Parent:
def __init__(self):
# useful stuff happens here

class Child:
def __init__(self):
Parent.__init__(self)
# other stuff, some useful, happens here

There are more sophisticated, less readable approaches, and I suspect
Python 2.2 or 2.3 add a new idiom as well.

-Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top