16.4. OOP Method Parameters

  • Methods are functions in the class

  • Prevents copy-paste code

  • Improves readability

  • Improves refactoring

  • Decomposes bigger problem into smaller chunks

  • 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.

Required parameter:

  • Necessary to call that function

  • Specified at leftmost side

Optional parameter:

  • Has default value

  • Optional to call that function

  • Default value will be overridden if specified at a call time

  • Specified at rightmost side

method

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

16.4.1. Without Parameters

>>> class User:
...     def login(self):
...         print(f'User login')

16.4.2. Required Parameters

  • At definition - self should always be a first parameter

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

  • Parameter - Receiving variable used within the function

  • Parameters could be required or optional (with default value)

>>> class User:
...     def login(self, username, password):
...         print(f'User login')

16.4.3. Optional Parameters

>>> class User:
...     def login(self, username=None, password=None):
...         print(f'User login')

16.4.4. Required and Optional Parameters

>>> class User:
...     def login(self, username, password=None):
...         print(f'User login')

16.4.5. Use Case - 0x01

>>> class User:
...     def login(self, username, password):
...         if username == 'mwatney' and password == 'nasa':
...             print('ok')
...         else:
...             raise PermissionError
...
>>>
>>>
>>> mark = User()
>>>
>>> mark.login()
Traceback (most recent call last):
TypeError: User.login() missing 2 required positional arguments: 'username' and 'password'
>>>
>>> mark.login('invalid', 'invalid')
Traceback (most recent call last):
PermissionError
>>>
>>> mark.login('mwatney', 'invalid')
Traceback (most recent call last):
PermissionError
>>>
>>> mark.login('invalid', 'nasa')
Traceback (most recent call last):
PermissionError
>>>
>>> mark.login('mwatney', 'nasa')
ok
>>>
>>> mark.login(username='mwatney', password='nasa')
ok

16.4.6. Assignments

"""
* Assignment: OOP Method One
* Type: class assignment
* Complexity: easy
* Lines of code: 2 lines
* Time: 2 min

English:
    1. Modify class `User`
    2. Define method `login` in class `User`
    3. Method prints 'User login'
    3. Run doctests - all must succeed

Polish:
    1. Zmodyfikuj klasę `User`
    2. Zdefiniuj metodę `login` w klasie `User`
    3. Metoda wypisuje 'User login'
    4. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from inspect import isclass, ismethod

    >>> assert isclass(User)
    >>> mark = User()
    >>> assert ismethod(mark.login)

    >>> mark.login()
    User login
"""

# Define method `login` in class `User`
# Method prints 'User login'
class User:
    ...

"""
* Assignment: OOP Method Two
* Type: class assignment
* Complexity: easy
* Lines of code: 2 lines
* Time: 2 min

English:
    1. Modify class `User`
    2. Define method `logout` in class `User`
    3. Method prints 'User logout'
    3. Run doctests - all must succeed

Polish:
    1. Zmodyfikuj klasę `User`
    2. Zdefiniuj metodę `logout` w klasie `User`
    3. Metoda wypisuje 'User logout'
    4. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from inspect import isclass, ismethod

    >>> assert isclass(User)
    >>> mark = User()
    >>> assert ismethod(mark.login)
    >>> assert ismethod(mark.logout)

    >>> mark.login()
    User login

    >>> mark.logout()
    User logout
"""

# Define method `logout` in class `User`
# Method prints 'User logout'
class User:
    def login(self):
        print('User login')


"""
* Assignment: OOP Method Parameters
* Type: class assignment
* Complexity: easy
* Lines of code: 4 lines
* Time: 3 min

English:
    1. Modify class `User`
    2. Modify method `login` in class `User`:
       a. Method takes `username` and `password` as arguments
       b. Method checks if username is 'mwatney' and password is 'Ares3'
       c. If true: method prints 'User login'
       d. If false: raise PermissionError with 'Invalid username or password'
    3. Run doctests - all must succeed

Polish:
    1. Zmodyfikuj klasę `User`
    2. Zmodyfikuj metodę `login` w klasie `User`:
        a. Metoda przyjmuje `username` i `password` jako argumenty
        b. Metoda sprawdza czy username to 'mwatney' i password to 'Ares3'
        c. Jeżeli prawda: metoda wypisuje 'User login'
        d. Jeżeli fałsz: rzuć PermissionError z 'Invalid username or password'
    3. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from inspect import isclass, ismethod

    >>> assert isclass(User)
    >>> mark = User()
    >>> assert ismethod(mark.login)
    >>> assert ismethod(mark.logout)

    >>> mark.login('mwatney', 'Ares3')
    User login

    >>> mark.login(username='mwatney', password='Ares3')
    User login

    >>> mark.login(username='mwatney', password='invalid')
    Traceback (most recent call last):
    PermissionError: Invalid username or password

    >>> mark.login(username='invalid', password='Ares3')
    Traceback (most recent call last):
    PermissionError: Invalid username or password

    >>> mark.login()
    Traceback (most recent call last):
    TypeError: User.login() missing 2 required positional arguments: 'username' and 'password'

    >>> mark.logout()
    User logout
"""

# Modify method `login` in class `User`:
# - Method takes `username` and `password` as arguments
# - Method checks if username is 'mwatney' and password is 'Ares3'
# - If true: method prints 'User login'
# - If false: raise PermissionError with 'Invalid username or password'
class User:
    def login(self):
        print('User login')

    def logout(self):
        print('User logout')