12.10. OOP Methods About

12.10.1. Rationale

  • Methods are functions in the class

  • Prevents copy-paste code

  • Improves readability

  • Improves refactoring

  • Decomposes bigger problem into smaller chunks

method

Functions in the class which takes instance as first argument (self)

self

Instance on which method was called.

12.10.2. Syntax

>>> class MyClass:
...     def mymethod(self):
...         pass
>>>
>>>
>>> my = MyClass()
>>> my.mymethod()

12.10.3. Define

  • At definition - self should always be a first parameter

>>> class Astronaut:
...     def say_hello(self):
...         print('hello')

12.10.4. Self

  • At definition - self should always be a first parameter

  • At call - self is not passed as an argument (Python will do that)

  • Later you will learn more advanced things like static methods etc.

12.10.5. Call

  • At call - self is not passed as an argument (Python will do that)

12.10.6. Return

12.10.7. Assignments