5.5. OOP Methods

5.5.1. Recap

  • Functions are instances of a class function

  • Functions have attributes

  • Functions have methods

  • Calling a __call__() method, will execute function

5.5.2. Recap

  • Functions are instances of a class function

  • Functions have attributes

  • Functions have methods

  • Functions are callable (they have __call__ method)

  • Calling a __call__() method, will execute function

>>> def login():
...     print('ok')

Functions are instances of a class function:

>>> type(login)
<class 'function'>

Functions have attributes:

>>> login.__name__
'login'
>>> login.__code__.co_code
b'\x95\x00[\x01\x00\x00\x00\x00\x00\x00\x00\x00S\x015\x01\x00\x00\x00\x00\x00\x00 \x00g\x00'

Functions have methods:

>>> login.__call__()
ok

Which is a shortcut for:

>>> login()
ok

5.5.3. Function or Method

  • Classes have functions

  • Instances have methods

  • On a class level, login is a function

  • On an instance level, login is a method

  • login becomes a method when we create an instance

>>> class User:
...     def login(self):
...         print('ok')
>>>
>>> mark = User()

On a class level, login is a function:

>>> type(User.login)
<class 'function'>

On an instance level, login is a method:

>>> type(mark.login)
<class 'method'>

login becomes a method when we create an instance.

5.5.4. Callable

  • Callable is an object that can be called (has __call__ method)

  • Instance fields are not callable

  • Instance methods are callable

  • Also class functions are callable

>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
...
...     def login(self):
...         print('ok')
>>>
>>> mark = User('Mark', 'Watney')

Instance fields are not callable:

>>> callable(mark.firstname)
False
>>>
>>> callable(mark.lastname)
False

Instance methods are callable:

>>> callable(mark.login)
True

Also class functions are callable:

>>> callable(User.login)
True