Basic Python Query

Fábio Santos fabiosantosart at gmail.com
Thu Aug 22 04:46:33 EDT 2013


On 22 Aug 2013 08:58, "chandan kumar" <chandan_psr at yahoo.co.in> wrote:
>
> Hi all,
>
> Sorry for not explaining question properly.Here Its not about threading
and dont worry about any indentations.Please see below example
>
> class Call_Constructor():
>     def __init__(self):
>         print "In __init__ "
>
> class Test_Constructor(Call_Constructor):
>     def method(self):
>        print " In Test_Constructor Class"
>
>   ConstructInstance = Test_Constructor()
>
> When an instace is created for Test_Constructor class ,The code flows
starts __init__ in Call_Constructor class.Whys is it like that.
>
>
> class Call_Constructor():
>     def __init__(self):
>         print "In __init__ "
>
>
> class Test_Constructor(Call_Constructor):
>     def  __init__(self):
>        print " In Test_Constructor Class"
>
>   ConstructInstance = Test_Constructor()
>
> But for the above case Code flows starts from Test_Constructor().
>
> Whats is the difference for both cases described above.
>
> Best Regards,
> Chandan.

When creating an instance, Python will call __init__. In the first example
there was only an __init__ method in the base class, so that one was used.
On the second example, there were __init__ methods on both classes, but
since you instantiated the subclass, the subclass's __init__ method was
executed.

Subclass methods have precedence over base class methods. If you want the
__init__ method of the base class in the second example to be called, you
can either remove the subclass __init__ method or call
super(TestConstructor, self).__init__() in that method. That will call the
base class's __init__.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130822/e4e2bc09/attachment.html>


More information about the Python-list mailing list