NEWBIE: Sub-classes revisited

engsolnom at ipns.com engsolnom at ipns.com
Wed Dec 31 18:47:06 EST 2003


Thanks for the patient help. My preconcieved notions
about sub-classes were wrong. After re-reading the
tutorial, and the responses to my postings, I think
I've learned a bit. (Hope so, anyway)

In the case of:

# IN MOD_1.PY

class B:
    def __init__ (self):
        self.B_init_var = 1
    def B_meth(self):
        self.B_meth_var = 2

# IN MOD_2.PY

import mod_1

class A(mod_1.B):              # B needs to be qualified
    def __init__(self):
        mod_1.B.__init__(self) # Needs to be qualified
        self.B_meth()          # But B's method doesn't
        print self.B_init_var  # Just to be sure
        print self.B_meth_var  # Ditto

obj = A()

Is the following true?

1. When A is instantiated, B's name space is exposed
   to A.
2. B is not instantiated when A is,
   therefore B's init is not run.
3. If A can't find B_meth in it's own namespace,
   it looks in B's namespace.
4. If one attempts to run B's init in A's init,
   using self.__init__(), one is in for a long wait...:)
5. B's init in A's init must be qualified to prevent #4
6. The proper terminology is:
   'A inherits B's methods and attributes'

7. An init in B is of limited usefulness.
8. If all one needs is to 'declare and inialize'
   variables common to a number of classes, one
   really doesn't need a base class,
   just a module containing the 'constants'. 
   But if there are methods which are semi-common
   to all sub-classes, and can be overidden or
   extended to do the job, then it makes sense to
   use inheritance.
9. Inheriting variables (only), then (always)
   over riding their values in the sub-classes
   doesn't save memory.

All comments welcome.
Thanks....Norm




More information about the Python-list mailing list