5.4. OOP Method About

  • name(self) - public method

  • _name(self) - protected method (non-public by convention)

  • __name(self) - private method (name mangling)

  • __name__(self) - system method

  • name_(self) - avoid name collision with built-ins

5.4.1. Recap

  • All functions are instances of a class function

  • All functions has attributes or methods such as __call__()

>>> def add(a, b):
...     return a + b
...
>>>
>>> type(add)
<class 'function'>
>>>
>>> add.__call__(1, 2)
3

5.4.2. Class Function

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

Let's check the type of a Astronaut.say_hello:

>>> type(Astronaut.say_hello)
<class 'function'>

Note, that say_hello() is a function not a method!!

What actually metod is? Is there a difference between method or a function? Is method a function on an instance?

>>> vars(Astronaut)  
mappingproxy({'__module__': '__main__',
              'say_hello': <function Astronaut.say_hello at 0x...>,
              '__dict__': <attribute '__dict__' of 'Astronaut' objects>,
              '__weakref__': <attribute '__weakref__' of 'Astronaut' objects>,
              '__doc__': None})

5.4.3. Method

>>> class Astronaut:
...     def say_hello(self):
...         return 'hello'
>>>
>>> astro = Astronaut()

Let's check the type of a astro.say_hello:

>>> type(astro.say_hello)
<class 'method'>

Note, that say_hello() is a method!!

5.4.4. Compare

5.4.5. Types

Dynamic method:

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

Static method:

>>> class MyClass:
...     def mymethod():
...         pass

Static method:

>>> class MyClass:
...     @staticmethod
...     def mymethod():
...         pass

Class method:

>>> class MyClass:
...     @classmethod
...     def mymethod(cls):
...         pass