[Tutor] Class in a class

Alan Gauld alan.gauld at freenet.co.uk
Fri Feb 18 00:27:11 CET 2005


> Does it make sense to do this:

That depends on what you are trying to do!
If its to make scrambled eggs thewn nope, no sense 
whatsoever, but if writing a programme storing an 
instance inside another instance is very common 
indeed! :-)

> In [2]: class AB:
>    ...:     pass
>    ...:
> In [3]: a = AB()
> 
> In [5]: class BC:
>    ...:     def __init__(self, foo):
>    ...:         self.foo = foo
> 
> In [6]: b = BC(a)


Indeed you can even store a class inside an object:

class C:
  def shout(self): print 'HELLO! from C'

class D:
  def shout(self): print 'HELLO! from D'

class A:
  def __init__(self,cls):
    self.c = cls

  def speak(self):
    print 'I'm an A but I have an object that says:'
    self.c().shout()

a = A(C)
b = A(D)

a.speak()
b.speak()

More commonly a method of A could also be created that 
returned an instance of C with certain A specific values.

The point of the example being simply that you can quite reasonably 
pass any PYthon object to a class/instance and it can be stored 
and later used or returned.

You can see a practical example of storing a class reference 
within an object in my Games Framework, described in the book 
of my tutorial (and the code is on Useless Python). 

HTH

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


More information about the Tutor mailing list