By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,984 Members | 2,832 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,984 IT Pros & Developers. It's quick & easy.

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

P: 2
Pls refer to the given below program:
Expand|Select|Wrap|Line Numbers
  1. class t2:
  2.     a=0
  3.     def _init_(self):
  4.         t2.a=10
  5.     def f1(self,temp):
  6.         self.a=temp
  7.     def f2(self):
  8.         print self.a
  9. O1=t2()
  10. O1.f2()
  11. O1.f1(1000)
  12. O1.f2()
  13. O1.a=2000
  14. O1.f2()
The result is :
0
1000
2000
And when called explicitly :
Expand|Select|Wrap|Line Numbers
  1. class t2:
  2.     a=0
  3.     def _init_(self):
  4.         t2.a=10
  5.     def f1(self,temp):
  6.         self.a=temp
  7.     def f2(self):
  8.         print self.a
  9. O1=t2()
  10. O1._init_()
  11. O1.f2()
  12. O1.f1(1000)
  13. O1.f2()
  14. O1.a=2000
  15. O1.f2()
gives us
10
1000
2000
Aug 5 '14 #1
Share this Question
Share on Google+
3 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
You have defined method "__init__" as "_init_". "__init__" (2 leading and trailing underscores) will be called when an instance is created, but not "_init_".
Aug 5 '14 #2

Expert 100+
P: 621
Also you are using both class and instance attributes named "a", which are not the same.
Expand|Select|Wrap|Line Numbers
  1. class T2:
  2.      a=0
  3.      def __init__(self):
  4.          T2.a=10
  5.      def f1(self,temp):
  6.          self.a=temp
  7.      def f2(self):
  8.          print self.a
  9.  
  10. class T3:
  11.     def __init__(self):
  12.         T2.a=20
  13.  
  14. O1=T2()
  15. O1.f2()
  16. O1.f1(1000)
  17. O1.f2()
  18. O1.a=2000
  19. O1.f2()
  20.  
  21. print T2.a
  22. third = T3()
  23. print T2.a 
Aug 5 '14 #3

P: 2
Verified.
Thanks for the guidance.
Aug 19 '14 #4

Post your reply

Sign in to post your reply or Sign up for a free account.