[Tutor] Re: Creating subclasses (newbie)

Andrei project5 at redrival.net
Thu Jun 24 03:02:31 EDT 2004


Adam <adam <at> monkeez.org> writes:

> I have a subclass I want to create - my intuition told me
> that it would be done like this:
> 
> class MainClass:
> 	class SubClass:
> 		code...
> 	subclassinstance = SubClass()
> mainclassinstance = MainClass()

Your intuition is wrong :). A subclass is not a class defined in a different
class, but a class that inherits and builds upon an ancestor class (a little bit
like a child inherits from her parents, but is not identical to them). For
example we know that all spheres have a diameter. We also know that all balls
are spheres and are intended for a certain game. However, not all spheres are
for playing games with (e.g. the sun or one of those glass "lightning" spheres).
So let's express that in classes:

class Sphere(object): # means Spere inherits from object
    def __init__(self, diameter):
        self.diameter = diameter
    def getRadius(self): # all spheres have a radius too
        return self.diameter/2

class Ball(Sphere): 
    # Ball inherits from (or is a subclass of) Sphere
    def __init__(self, diameter, game):
        Sphere.__init__(self, diameter) 
                # initializes the Sphere properties
                # (which Ball obviously also has)
        self.game = game # a Ball is meant to play a certain game

football = Ball(14.0, 'football') # instance of Ball
sun = Sphere(1.4e11) # instance of Sphere

print football.getRadius() 
  # method inherited by Ball from Sphere
  # Subclassing Sphere got us all its functionality
  # for free! If you need more sphere-like objects,
  # like a Planet class, they too will inherit all
  # functionality shared by all Spheres.

print football.game # will print game property of Ball instance.

print sun.game # will give an error message, since Sphere does
               # not inherit anything from Ball (parents don't 
               # inherit anything from their children!)

> But it seems that this isn't going to work. I'm reading a
> couple of Python books, but they don't seem to cover this
> topic very well (I don't see any coding examples).

You should look a bit better :). People on the main Python mailing list have
already pointed you to some tutorials, so read those and all will be clear(er).

Yours,

Andrei




More information about the Tutor mailing list