5.4. OOP Methods

5.4.1. Recap

  • Functions are instances of a class function

  • Functions have attributes

  • Functions have methods

  • Calling a __call__() method, will execute function

5.4.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'\x80\x00\\\x01\x00\x00\x00\x00\x00\x00\x00\x00R\x004\x01\x00\x00\x00\x00\x00\x00\x1f\x00R\x01#\x00'

Functions have methods:

>>> login.__call__()
ok

Which is a shortcut for:

>>> login()
ok

5.4.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')
>>>
>>> obj = User()

On a class level, login is a function:

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

On an instance level, login is a method:

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

login becomes a method when we create an instance.

5.4.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')
>>>
>>> obj = User('Alice', 'Apricot')

Instance fields are not callable:

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

Instance methods are callable:

>>> callable(obj.login)
True

Also class functions are callable:

>>> callable(User.login)
True