_init() not called automatically , when an object is made.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Neeta Singh
    New Member
    • Aug 2014
    • 2

    _init() not called automatically , when an object is made.

    Pls refer to the given below program:
    Code:
    class t2:
        a=0
        def _init_(self):
            t2.a=10
        def f1(self,temp):
            self.a=temp
        def f2(self):
            print self.a
    O1=t2()
    O1.f2()
    O1.f1(1000)
    O1.f2()
    O1.a=2000
    O1.f2()
    The result is :
    0
    1000
    2000
    And when called explicitly :
    Code:
    class t2:
        a=0
        def _init_(self):
            t2.a=10
        def f1(self,temp):
            self.a=temp
        def f2(self):
            print self.a
    O1=t2()
    O1._init_()
    O1.f2()
    O1.f1(1000)
    O1.f2()
    O1.a=2000
    O1.f2()
    gives us
    10
    1000
    2000
    Last edited by bvdet; Aug 5 '14, 01:47 PM. Reason: Add code tags
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    You have defined method "__init__" as "_init_". "__init__" (2 leading and trailing underscores) will be called when an instance is created, but not "_init_".

    Comment

    • dwblas
      Recognized Expert Contributor
      • May 2008
      • 626

      #3
      Also you are using both class and instance attributes named "a", which are not the same.
      Code:
      class T2:
           a=0
           def __init__(self):
               T2.a=10
           def f1(self,temp):
               self.a=temp
           def f2(self):
               print self.a
      
      class T3:
          def __init__(self):
              T2.a=20
      
      O1=T2()
      O1.f2()
      O1.f1(1000)
      O1.f2()
      O1.a=2000
      O1.f2()
      
      print T2.a
      third = T3()
      print T2.a

      Comment

      • Neeta Singh
        New Member
        • Aug 2014
        • 2

        #4
        Verified.
        Thanks for the guidance.

        Comment

        Working...