11.12. Operator Contains

  • in - contains

  • y in x - will call "contains" on object x (x.__contains__(y))

11.12.1. Example

>>> class Crew:
...     def __init__(self):
...         self.members = []
...
...     def __iadd__(self, astronaut):
...         self.members.append(astronaut)
...         return self
...
...     def __contains__(self, astronaut):
...         for member in self.members:
...             if member == astronaut:
...                 return True
...         return False
>>>
>>>
>>> ares3 = Crew()
>>> ares3 += 'Mark Watney'
>>> ares3 += 'Melissa Lewis'
>>> ares3 += 'Rick Martinez'
>>>
>>>
>>> 'Mark Watney' in ares3
True
>>>
>>> 'Alex Vogel' in ares3
False

11.12.2. Assignments

Code 11.31. Solution
"""
* Assignment: Operator Comparison Contains
* Complexity: easy
* Lines of code: 5 lines
* Time: 8 min

English:
    1. Override operators for code to work correctly
    2. Do not use `dataclasses`
    3. Run doctests - all must succeed

Polish:
    1. Nadpisz operatory aby poniższy kod zadziałał poprawnie
    2. Nie używaj `dataclasses`
    3. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * `object.__contains__()`
    * `object.__eq__()`

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> astro = Astronaut(firstname='Mark', lastname='Watney', missions=[
    ...     Mission(1969, 'Apollo 11'),
    ...     Mission(2024, 'Artemis 3'),
    ...     Mission(2035, 'Ares 3'),
    ... ])

    >>> Mission(2035, 'Ares 3') == Mission(2035, 'Ares 3')
    True
    >>> Mission(2035, 'Ares 3') == Mission(1973, 'Apollo 18')
    False
    >>> Mission(2035, 'Ares 3') == Mission(2035, 'Apollo 18')
    False
    >>> Mission(2035, 'Ares 3') == Mission(1973, 'Ares 3')
    False

    >>> Mission(2024, 'Artemis 3') in astro
    True
    >>> Mission(1973, 'Apollo 18') in astro
    False
"""


class Mission:
    year: int
    name: str

    def __init__(self, year: int, name: str) -> None:
        self.year = year
        self.name = name


class Astronaut:
    firstname: str
    lastname: str
    missions: list

    def __init__(self, firstname: str, lastname: str, missions: list) -> None:
        self.firstname = firstname
        self.lastname = lastname
        self.missions = missions