Overriding __init__() questions

Terry Reedy tjreedy at udel.edu
Sat Apr 11 23:42:05 CEST 2009


grocery_stocker wrote:
> What's the difference between doing something calling A.__init__(self)
> like in the following...
> 
> [cdalten at localhost ~]$ python
> Python 2.4.3 (#1, Oct  1 2006, 18:00:19)
> [GCC 4.1.1 20060928 (Red Hat 4.1.1-28)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> class A:
> ...    def __init__(self):
> ...       pass
> ...
>>>> class B(A):
> ...    def __init__(self, x):
> ...        A.__init__(self)
> ...        self.x = x
> ...        print x
> ...
>>>> x=B(5)
> 5
>>>> y=A(5)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: __init__() takes exactly 1 argument (2 given)
>>>> y = A()
>>>>
> 
> versus something like the following....
> 
> [cdalten at localhost ~]$ python
> Python 2.4.3 (#1, Oct  1 2006, 18:00:19)
> [GCC 4.1.1 20060928 (Red Hat 4.1.1-28)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> class A:
> ...    def __init__(self):
> ...       pass
> ...
>>>> class B(A):
> ...    def __init__(self, x):
> ...        self.x = x
> ...        print x

In one you call A.__init__ and the other you don't.  If A.__init__ does 
something useful, as it usually would, then not calling it would not get 
that useful work done.  Or you repeat the useful code of A.__init__ in 
B.__init__, which is not a good idea, especially when you have to change 
that code in two places.

> ...
>>>> x = B(5)
> 5
>>>> y = A(5)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: __init__() takes exactly 1 argument (2 given)
>>>> y = A()
>>>>
> 
> Just curious because the former seems to be common when using the
> python Thread module.
> --
> http://mail.python.org/mailman/listinfo/python-list
> 




More information about the Python-list mailing list