[Tutor] Class Inheritance

Eric Brunson brunson at brunson.com
Thu Sep 13 23:32:34 CEST 2007


Lamonte Harris wrote:
> Okay
>
> class A:
>    def __init__(self,x,y):
>      self.x = x
>      self.y = y
>
>    def save(self,fn):
>      f = open(fn,"w")
>      f.write(str(self.x)+ '\n') 
> # convert to a string and add newline
>      f.write(str(self.y)+'\n')
>      return f             # for child objects to use
>
>    def restore(self, fn):
>      f = open(fn)
>
>      self.x = int(f.readline()) # convert back to original type
>      self.y = int(f.readline())
>      return f
>      
> class B(A):
>    def __init__(self,x,y,z):
>      A.__init__(self,x,y)
>
>      self.z = z
>    
>    def save(self,fn):
>      f = A.save(self,fn)  # call parent save
>      f.write(str(self.z)+'\n')
>      return f         # in case further children exist
>
>    
>    def restore(self, fn):
>      f = A.restore(self,fn)
>      self.z = int(f.readline())
>      return f
> In the class B,  I'm not understanding the A.__init(self,x,y) part.  
> So its initializing the class A, and basically you can use the A class 
> like normal?

Essentially, yes, but the way you've worded it is imprecise.  Any 
instance of B is a subclass of A, essentially an A:  Every boy is a 
male, but not all males are boys.  When you override a method in a 
subclass you have essentially turned off all behavior in the parent 
method, including "magic" methods like the constructor.  You have to 
call the parent constructor explicitly to get its benefits.

A method of an instance can be called like this:  instance.method() and 
python makes sure that a pointer to the instance is passed in as the 
first argument, generally "self".  But a method of a class can be called 
without instantiating the class, but you have to supply "self" on you own.

The method you are using is valid,  yet depricated.  Using "new style 
classes" (which aren't actually that new) you'd write your code like this:

class A(object):
    def __init__(self, a):
        self.aye = a

class B(A):
    def __init__(self, a, b):
        self.bee = b
        super( B, self ).__init__( a )

Notice that you don't have to supply self.

You can use any method of A in an instance of B that you haven't 
overridden in B without having to use super().

> Part im confused about is the self.z, does that belong to the class A 
> or class B?  

z is an attribute B only.

Hope that helps,
e.

> Else I think I'm understanding it correctly.
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



More information about the Tutor mailing list