why am I not allowed to redefine a class ?

Arnaud Delobelle arnodel at googlemail.com
Sun Nov 9 07:48:28 EST 2008


Stef Mientki <stef.mientki at gmail.com> writes:

> hello,
>
> although this is not a real problem for me,
> it was caused by a copying, instead of moving, a piece of code.
> But I don't understand at all why the code below gives the error.
> class derived_class, is defined twice,
> the error is cuase by the second instance creation "test2="
> for me even weirder, if I create test2 in another module, everything
> works perfect ???
> Any explanation would be welcome.
> thanks,
> Stef Mientki
>
> ==== start of code ===
> class base_class ( object ) :
>  def __init__ ( self ) :
>    pass
>
> class derived_class ( base_class ) :
>  def __init__ ( self ) :
>    base_class.__init__ ( self )
>
> class final_class_1 ( derived_class ) :
>  def __init__ ( self ) :
>    derived_class.__init__ ( self )
>
> test1 = final_class_1 ()
>
> class derived_class ( base_class ) :
>  def __init__ ( self ) :
>    base_class.__init__ ( self )
>
> test2 = final_class_1 ()
> ==== end of code =====
>
> ==== error meassage =====
> Traceback (most recent call last):
>  File "D:\Data_Python_25\PyLab_Works\module1.py", line 19, in <module>
>    test2 = final_class_1 ()
>  File "D:\Data_Python_25\PyLab_Works\module1.py", line 11, in __init__
>    derived_class.__init__ ( self )
> TypeError: unbound method __init__() must be called with derived_class
> instance as first argument (got final_class_1 instance instead)

Because after rebinding 'derived_class', the class 'final_class_1' is
not a subclass of 'derived_class'

One solution is to ensure you bind the word 'derived_class' to the
correct class:

class final_class_1(derived_class):
    def __init__(self, derived_class=derived_class):
        derived_class.__init__ ( self )

This should work (untested).

It's worth noting that one can avoid this problem in Python 3 by using
super():

>>> class A:
...     def __init__(self): print('init A')
... 
>>> class B(A):
...     def __init__(self):
...         super().__init__()
... 
>>> b=B()
init A
>>>

-- 
Arnaud



More information about the Python-list mailing list