Advertisement
furas

Python - staticmethod, classmethod, method

May 18th, 2017
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. class Example:
  2.    
  3.     class_variable = 'Hello'
  4.    
  5.     @staticmethod
  6.     def a():
  7.         return 'A'
  8.  
  9.     def b():
  10.         return 'B'
  11.  
  12.     @classmethod
  13.     def c(cls):
  14.         cls.a()
  15.         cls.b()
  16.         #cls.d() # ERROR: method need instance
  17.         return 'C', cls, cls.class_variable
  18.  
  19.     def d(self):
  20.         self.a()
  21.         #self.b() # ERROR: method doesn't need instance
  22.         self.c()
  23.         return 'D', self, self.class_variable
  24.  
  25.  
  26. e = Example()
  27.  
  28. print('Example.a:', Example.a)
  29. print('Example.b:', Example.b)
  30. print('Example.c:', Example.c)
  31. print('Example.d:', Example.d)
  32. print('-------')
  33. print('Example.a():', Example.a())
  34. print('Example.b():', Example.b())
  35. print('Example.c():', Example.c())
  36. try:
  37.     print('Example.d():', Example.d())
  38. except Exception as ex:  
  39.     print('Example.d():')
  40.     print('  ERROR:', ex)
  41.     print("  ERROR: method need instance")
  42.  
  43. #print(Example.d(Example))
  44. print('-------')
  45. print('e.a:', e.a)
  46. print('e.b:', e.b)
  47. print('e.c:', e.c)
  48. print('e.d:', e.d)
  49. print('-------')
  50. print('e.a():', e.a())
  51. try:
  52.     print('e.b():', e.b())
  53. except Exception as ex:  
  54.     print('e.b():')
  55.     print('  ERROR:', ex)
  56.     print("  ERROR: method doesn't need instance")
  57. print('e.c():', e.c())
  58. print('e.d():', e.d())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement