methodtypes.py 754 B

123456789101112131415161718192021222324
  1. #!/usr/bin/env python3
  2. """ Demonstrates the difference between an instance method,
  3. a class method, and a static method.
  4. """
  5. class MyClass:
  6. # Instance method. Have to instantiate an instance
  7. # first! And it can change all the stuff that is
  8. # unique to that instance. (It can also change
  9. # the class itself, if it wants to, by accessing
  10. # self.__class__
  11. def method(self):
  12. return 'instance method called', self
  13. # The class method doesn't need an object to be
  14. # instantiated. It just is.
  15. @classmethod
  16. def classmethod(cls):
  17. return 'class method called', cls
  18. # Static methods don't even get access to the class
  19. @staticmethod
  20. def staticmethod():
  21. return 'static method called'