__init__() not called automatically

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Sriek

    __init__() not called automatically

    hi,
    i come from a c++ background. i ws happy to find myself on quite
    familiar grounds with Python. But, what surprised me was the fact that
    the __init__(), which is said to be the equivlent of the constructor in
    c++, is not automatically called. I'm sure there must be ample reason
    for this. I would like to know why this is so? This is my view is more
    burden on the programmer.
    Similarly, why do we have to explicitly use the 'self' keyword
    everytime?

    Every kind of help would be welcome.

  • Tim Leslie

    #2
    Re: __init__() not called automatically

    On 25 May 2005 21:31:57 -0700, Sriek <scharan20@gmai l.com> wrote:[color=blue]
    > hi,
    > i come from a c++ background. i ws happy to find myself on quite
    > familiar grounds with Python. But, what surprised me was the fact that
    > the __init__(), which is said to be the equivlent of the constructor in
    > c++, is not automatically called. I'm sure there must be ample reason
    > for this. I would like to know why this is so? This is my view is more
    > burden on the programmer.[/color]
    [color=blue][color=green][color=darkred]
    >>> class C:[/color][/color][/color]
    .... def __init__(self): print "Hello"
    ....[color=blue][color=green][color=darkred]
    >>> c = C()[/color][/color][/color]
    Hello

    This looks like __init__ being called automatically to me. Are you
    doing something different?
    [color=blue]
    > Similarly, why do we have to explicitly use the 'self' keyword
    > everytime?[/color]


    [color=blue]
    >
    > Every kind of help would be welcome.[/color]

    No worries,

    Tim
    [color=blue]
    >
    > --
    > http://mail.python.org/mailman/listinfo/python-list
    >[/color]

    Comment

    • Paul McNett

      #3
      Re: __init__() not called automatically

      Sriek wrote:[color=blue]
      > hi,
      > i come from a c++ background. i ws happy to find myself on quite
      > familiar grounds with Python. But, what surprised me was the fact that
      > the __init__(), which is said to be the equivlent of the constructor in
      > c++, is not automatically called.[/color]

      What do you mean by automatically? :

      Python 2.4.1 (#2, May 5 2005, 09:45:41)
      [GCC 4.0.0 20050413 (prerelease) (Debian 4.0-0pre11)] on linux2
      Type "help", "copyright" , "credits" or "license" for more information.[color=blue][color=green][color=darkred]
      >>> class A(object):[/color][/color][/color]
      .... def __init__(self):
      .... print "in __init__"
      ....[color=blue][color=green][color=darkred]
      >>> a = A()[/color][/color][/color]
      in __init__

      So __init__ is definitely called upon instantiation. It is true that if
      you derive from A and override __init__, A.__init__ won't be called
      unless done so explicitly like:

      class B(A):
      def __init__(self):
      print "in B.__init__()"
      super(B, self).__init__( )
      [color=blue]
      > I'm sure there must be ample reason
      > for this. I would like to know why this is so? This is my view is more
      > burden on the programmer.[/color]

      It isn't that much practical burden, and IMO it makes perfect sense.
      When you override a method of a class, you want to have to explicitly
      call superclass code, not have it run automatically, else you lose
      control of the flow.

      [color=blue]
      > Similarly, why do we have to explicitly use the 'self' keyword
      > everytime?[/color]

      This is closer to a wart, IMO, but once you've used Python for a while
      you'll come to understand why this is so. Basically, everything in
      Python is either a namespace or a name in a namespace. In the case of
      the self reference which Python sends as the first arg automatically,
      the method needs to bind that to a local name which is, by convention
      only, 'self'.

      [color=blue]
      > Every kind of help would be welcome.[/color]

      You've found the right place to hang out. Welcome!


      --
      pkm ~ http://paulmcnett.com

      Comment

      • Sriek

        #4
        Re: __init__() not called automatically

        Tim pointed out rightly that i missed out the most crucial part of my
        question.
        i should have said that __init__() is not called automatically only for
        the inheritance hierarchy. we must explicitly call all the base class
        __init__() fuctions explicitly.
        i wanted a reason for that.
        Thanks Tim.

        Comment

        • Steven Bethard

          #5
          Re: __init__() not called automatically

          Paul McNett wrote:[color=blue]
          > Sriek wrote:[color=green]
          >> i come from a c++ background. i ws happy to find myself on quite
          >> familiar grounds with Python. But, what surprised me was the fact that
          >> the __init__(), which is said to be the equivlent of the constructor in
          >> c++, is not automatically called.[/color]
          >[/color]
          [snip][color=blue]
          >
          > It is true that if
          > you derive from A and override __init__, A.__init__ won't be called
          > unless done so explicitly like:
          >
          > class B(A):
          > def __init__(self):
          > print "in B.__init__()"
          > super(B, self).__init__( )
          >[color=green]
          >> I'm sure there must be ample reason
          >> for this. I would like to know why this is so? This is my view is more
          >> burden on the programmer.[/color]
          >
          > It isn't that much practical burden, and IMO it makes perfect sense.
          > When you override a method of a class, you want to have to explicitly
          > call superclass code, not have it run automatically, else you lose
          > control of the flow.[/color]

          I'd like to reiterate this point. Say I have a class like:

          class A(object):
          def __init__(self, x):
          self.x = x
          print 'A.__init__'

          and an inheriting class like:

          class B(A):
          def __init__(self, y):
          ...
          print 'B.__init__'
          ...

          If 'y' is the same thing as 'x', then I probably want to write B like:

          class B(A):
          def __init__(self, y):
          super(B, self).__init__( y)
          print 'B.__init__'

          But what if 'x' has to be computed from 'y'? Then I don't want the
          super call first. I probably want it last (or at least later), e.g.:

          class B(A):
          def __init__(self, y):
          print 'B.__init__'
          x = self._compute_x (y)
          super(B, self).__init__( x)

          If the superclass constructor is automatically called, how will it know
          which meaning I want for 'y'? Is 'y' equivalent to 'x', or is it
          something different? Since Python can't possibly know this for sure, it
          refuses the temptation to guess, instead requiring the user to be explicit.

          STeVe

          Comment

          • Sakesun Roykiattisak

            #6
            Re: __init__() not called automatically

            Does c++ call base class constructor automatically ??
            If I'm not wrong, in c++ you also have to call base class constructor
            explicitly.
            Python just do not enforce the rule. You can leave it as desire.

            BTW, I've once been an C++ expert. Knowing python kill that skill.
            However, I'm not regret. I have c++ compiler installed, but I don't even
            bother validate my last paragraph assertion. Too disgusting. ;)

            Sriek wrote:
            [color=blue]
            >Tim pointed out rightly that i missed out the most crucial part of my
            >question.
            >i should have said that __init__() is not called automatically only for
            >the inheritance hierarchy. we must explicitly call all the base class
            >__init__() fuctions explicitly.
            > i wanted a reason for that.
            >Thanks Tim.
            >
            >[/color]

            Comment

            • Sriek

              #7
              Re: __init__() not called automatically

              if i understand C++ right, in c++ you CAN explicitly call the base
              constructor ( for eg. if it requires some particular arguements ), but,
              the compiler automatically has to call the base class constructor ( see
              the rules for constructing an object of the derived classes ).

              But, yes, C++ can be too disgusting sometimes. But, i like the C++
              design philosophy ( read D & E of C++ ? ), the rasons for various
              features are intellgently put inplace.

              Correct me if i am wrong about both the paragraphs. ok? T
              Thanks

              Comment

              • Sriek

                #8
                Re: __init__() not called automatically

                maybe like this:
                we can have the default behaviour as calling the default constructor
                ( with default arguements where required ). Along with this, keep the
                option open to call constructors explicitly.

                My only contention is that there may be a greater reason for this rule
                in the Python Language. thats it.

                Comment

                • Jeremy Sanders

                  #9
                  Re: __init__() not called automatically

                  On Wed, 25 May 2005 21:31:57 -0700, Sriek wrote:
                  [color=blue]
                  > Similarly, why do we have to explicitly use the 'self' keyword everytime?[/color]

                  I didn't like that when starting Python. Now when I look back at C++ code,
                  I find it very hard to work out which variables and methods and members,
                  and which are not, unless the author used a clear naming convention.

                  Jeremy

                  Comment

                  • John Roth

                    #10
                    Re: __init__() not called automatically


                    "Sriek" <scharan20@gmai l.com> wrote in message
                    news:1117081917 .760603.82610@z 14g2000cwz.goog legroups.com...[color=blue]
                    > hi,
                    > i come from a c++ background. i ws happy to find myself on quite
                    > familiar grounds with Python. But, what surprised me was the fact that
                    > the __init__(), which is said to be the equivlent of the constructor in
                    > c++, is not automatically called. I'm sure there must be ample reason
                    > for this. I would like to know why this is so? This is my view is more
                    > burden on the programmer.[/color]

                    It depends on what you mean by a burden. If the init methods of
                    each subclass was always called, then you'd have to work out how
                    to make them cooperate in all cases. The way C++ works, it has to
                    call the constructors because the vtable has explicit sections for each
                    of the base classes, recursively to the (possibly multiple) bases of
                    the tree. In Python, that isn't true - you get one instance regardless
                    of the number of base classes or structure of the tree, and that
                    single instance contains all the identifiers needed. It's up to the
                    class you instantiate to decide how to build the instance.
                    [color=blue]
                    > Similarly, why do we have to explicitly use the 'self' keyword
                    > everytime?[/color]

                    Python has no way of knowing, at compile time, whether an
                    identifier is an instance/class variable or a module/builtin.
                    Putting the instance among the parameters lets you treat it as
                    a local variable which the compiler is quite capable of handling.

                    Remember that you're dealing with a highly dynamic environment;
                    inspection of the single source module will not tell you enough to
                    make this distinction.

                    John Roth[color=blue]
                    >
                    > Every kind of help would be welcome.
                    >[/color]

                    Comment

                    • Dan Sommers

                      #11
                      Re: __init__() not called automatically

                      On 25 May 2005 21:31:57 -0700,
                      "Sriek" <scharan20@gmai l.com> wrote:
                      [color=blue]
                      > Similarly, why do we have to explicitly use the 'self' keyword
                      > everytime?[/color]

                      Why do they (the C++ programmers) prepend "m_" to otherwise perfectly
                      good member names?

                      Regards,
                      Dan

                      --
                      Dan Sommers
                      <http://www.tombstoneze ro.net/dan/>

                      Comment

                      • Andrew Koenig

                        #12
                        Re: __init__() not called automatically

                        "Sakesun Roykiattisak" <sakesun@boonth avorn.com> wrote in message
                        news:mailman.12 2.1117088782.18 027.python-list@python.org ...
                        [color=blue]
                        > Does c++ call base class constructor automatically ??
                        > If I'm not wrong, in c++ you also have to call base class constructor
                        > explicitly.[/color]

                        In C++, if you don't call a base-class constructor (I am saying "a" rather
                        than "the" because there might be more than one direct base class), it is
                        called automatically with no arguments. The only case in which you must
                        call it explicitly is if it will not accept an empty argument list.


                        Comment

                        • Steven Bethard

                          #13
                          Re: __init__() not called automatically

                          Sriek wrote:[color=blue]
                          > maybe like this:
                          > we can have the default behaviour as calling the default constructor
                          > ( with default arguements where required ). Along with this, keep the
                          > option open to call constructors explicitly.[/color]

                          Ok, so here's another example:

                          def init(self):
                          print "An __init__ method, but in what class?!!"
                          print "Oh, this class: %s" % type(self).__na me__

                          class C(object):
                          pass

                          C.__init__ = init

                          So how would the compiler know that init() is a constructor for the C
                          object? (You can figure that out at runtime, but I don't see how you can
                          generally figure that out at compile time.)

                          STeVe

                          Comment

                          • Sri Charan

                            #14
                            Re: __init__() not called automatically

                            I guess you are right.

                            Comment

                            • Sri Charan

                              #15
                              Re: __init__() not called automatically

                              The compiler also calls the default arguement constructor
                              automatically, if such a constructor is provided for the base
                              class(es); but, this becomes a special case of what has been said by
                              Andrew Koenig.

                              So, it is NOT just the no arguement constructor that is automatically
                              called; note that the default arguement constructor is kinda put in
                              place because sometimes, the user may call the constructor with no
                              arguements, while the object actually needs some values for proper
                              construction.

                              Comment

                              Working...