[Tutor] Classes

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 4 Apr 2001 00:45:10 -0700 (PDT)


On Tue, 3 Apr 2001, VanL wrote:

> Here is my second question:
> 
> I am investigating python's inheritance structure.  Given the class
> LinkedList:
> 
> class LinkedList:
>     
>     """ This class provides a generic node for linked lists.  Other
> python classes or
>     objects can inherit from this class to get the ability to represent
> themselves as
>     a linked list. """
> 
>     def __init__(self, name, object=None):
>         self.__label = name
>         if object: self.__link = object
>         else: self.__link = None
> 
> [snip to end]
> 
> 
> and the class NewClass:
> 
> class NewClass(LinkedList):
> 	
> 	def __init__(self):
> 		NewString = "This is a new string"
> 
> 	def NewString(self):
> 		print NewString
> 
> 
> How do I supply the superclass constructor arguments when instancing an
> object of type newclass?  How does this change if I inherit from
> multiple classes?

In Python, you'll need to call the superclass's constructor explicitely.  
If you're coming from a Java or C++ background, this will come as a small
shock, since those languages take implicit steps to get constructors to
run.

Here's a definition of NewClass's constructor that calls the parent's
constructor:


###
class NewClass(LinkedList):
    def __init__(self):
        LinkedList.__init__(self)       # Calling superclass's constructor
        NewString = "This is a new string"
###


Dealing with multiple inheritance is similar: just call each parent's
init function.

Another way to do it is to be a little more implicit: every instance
implicitely knows where it came from, that is, what class it's from.  For
example, we can say something like:

    self.__class__

and get access to the class, which is pretty neat.  But more importantly,
we can get to the parents of any particular class through the __bases__ of
a class:

###
>>> class Parent:
...    def __init__(self):
...        print "I am a parent"
...
>>> p = Parent()
I am a parent
>>> class Child(Parent):
...     def __init__(self):
...         print self.__class__.__bases__, 'is a tuple of my parents.'
...         self.__class__.__bases__[0]()   # Call the parent's
constructor
...         print "End of child's constructor"
...
>>> c = Child()
(<class __main__.Parent at 80cbf20>,) is a tuple of my parents.
I am a parent
End of child's constructor
###


I know I'm going a little too fast and informal, but I hope this gives a
taste of how to call parent constructors.  Hope this helps!