[Tutor] Importing modules/classes

Alan Gauld alan.gauld at btinternet.com
Thu Aug 25 09:58:05 CEST 2005


> class show_num(threading.Thread):
>
>    def __init__(self, num):
>        print "__init__: Num = ", num
>
> show_num_thread = show_num(742)
> show_num_thread.start()
>
> ---><-----
>
> Throws an error
>
>>>>
> __init__: Num =  742
>
> Traceback (most recent call last):
>  File "H:/Docs/PyScripts/test_thread_1.py", line 12, 
> in -toplevel-
>    show_num_thread.start()
> AssertionError: Thread.__init__() not called
>>>>
>
> Which __init__ method is it referring to?

You need to call the init method of the inherited class(es) from
within your init. It's conventional to call the superclass 
constructor
before doing your own initialisation so it should look like:

    def __init__(self, num):
        Thread.__init__(self)
        print "__init__: Num = ", num

There is a new technique for doing this in recent Python version
(v2.2 onwards?) using the super keyword, but I've still to get
my own head around it... :-)

By calling the superclass first that means that your init code 
can
safely call features of the superclass, sure that they are going 
to work OK.

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