code_junkie

Python - why use “self” in a class

Nov 13th, 2011
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. class A():
  2. x=3
  3.  
  4. class B():
  5. def __init__(self):
  6. self.x=3
  7.  
  8. #!/usr/bin/env python
  9.  
  10. class A:
  11. x = []
  12.  
  13. def add(self):
  14. self.x.append(1)
  15.  
  16.  
  17. class B:
  18. def __init__(self):
  19. self.x = []
  20.  
  21. def add(self):
  22. self.x.append(1)
  23.  
  24.  
  25. x = A()
  26. y = A()
  27. x.add()
  28. y.add()
  29. print "A's x:",x.x
  30.  
  31. x = B()
  32. y = B()
  33. x.add()
  34. y.add()
  35. print "B's x:",x.x
  36.  
  37. >>> class A:
  38. ... def __init__(s):
  39. ... s.bla = 2
  40. ...
  41. >>>
  42. >>> a = A()
  43. >>> a.bla
  44. 2
  45.  
  46. >>> class Foo():
  47. ... i = 3
  48. ... def bar(self):
  49. ... print 'Foo.i is', Foo.i
  50. ... print 'self.i is', self.i
  51. ...
  52. >>> f = Foo() # Create an instance of the Foo class
  53. >>> f.bar()
  54. Foo.i is 3
  55. self.i is 3
  56. >>> Foo.i = 5 # Change the global value of Foo.i over all instances
  57. >>> f.bar()
  58. Foo.i is 5
  59. self.i is 5
  60. >>> f.i = 3 # Override this instance's definition of i
  61. >>> f.bar()
  62. Foo.i is 5
  63. self.i is 3
Add Comment
Please, Sign In to add comment