16.5. OOP Method Arguments

  • Methods are functions in the class

  • Prevents copy-paste code

  • Improves readability

  • Improves refactoring

  • Decomposes bigger problem into smaller chunks

  • At this moment:

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

method

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

16.5.1. Method 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)

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

Without parameters:

>>> class Astronaut:
...     def say_hello(self):
...         print('My name... José Jiménez')

Methods with required parameter:

>>> class Astronaut:
...     def say_hello(self, firstname):
...         print(f'My name... {firstname}')

Method with optional parameter:

>>> class Astronaut:
...     def say_hello(self, firstname='unknown'):
...         print(f'My name... {firstname}')

Method with required and optional parameter:

>>> class Astronaut:
...     def say_hello(self, firstname, lastname='unknown'):
...         print(f'My name... {firstname} {lastname}')

16.5.2. Method Arguments

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

>>> class Astronaut:
...     def say_hello(self):
...         print('My name... José Jiménez')
...
...
>>> jose = Astronaut()
>>> jose.say_hello()
My name... José Jiménez

Method with positional argument:

>>> class Astronaut:
...     def say_hello(self, name):
...         print(f'My name... {name}')
>>>
>>>
>>> jose = Astronaut()
>>>
>>> jose.say_hello('José Jiménez')
My name... José Jiménez
>>>
>>> jose.say_hello()
Traceback (most recent call last):
TypeError: Astronaut.say_hello() missing 1 required positional argument: 'name'

Method with keyword argument:

>>> class Astronaut:
...     def say_hello(self, firstname, lastname):
...         print(f'My name... {firstname} {lastname}')
>>>
>>>
>>> jose = Astronaut()
>>>
>>> jose.say_hello(firstname='José', lastname='Jiménez')
My name... José Jiménez
>>>
>>> jose.say_hello(lastname='Jiménez', firstname='José')
My name... José Jiménez
>>>
>>> jose.say_hello()
Traceback (most recent call last):
TypeError: Astronaut.say_hello() missing 2 required positional arguments: 'firstname' and 'lastname'

16.5.3. 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')