12.4. OOP Attribute Set

12.4.1. Syntax

  • Optional attribute annotation

>>> class MyClass:
...     myattribute: str

12.4.2. Example

>>> class Astronaut:
...     pass
>>> class Astronaut:
...     firstname: str
...     lastname: str

12.4.3. Namespace

Unrelated values:

>>> x: int
>>> y: int
>>> z: int

Class creates space, in which names has meaning:

>>> class Point:
...     x: int
...     y: int
...     z: int

12.4.4. Different Types

>>> class Iris:
...     features: list[float]
...     label: str
>>> 
... class Astronaut:
...     firstname: str
...     lastname: str
...     age: float|int
...     height: float
...     weight: float
...     missions: list
...     experience: list|None

12.4.5. Relation One to One

>>> class Date:
...     year: int
...     month: int
...     day: int
>>>
>>>
>>> class Person:
...     firstname: str
...     lastname: str
...     date_of_birth: Date

12.4.6. Relation One to Many

>>> class Mission:
...     year: int
...     name: str
>>>
>>>
>>> class Astronaut:
...     firstname: str
...     lastname: str
...     missions: list[Mission]

12.4.7. Use Case - 0x01

>>> class Laptop:
...     cpu: float
...     ram: int
...     ssd: int

12.4.8. Use Case - 0x02

>>> class Date:
...     year: int
...     month: int
...     day: int

12.4.9. References

glassimg

https://media.istockphoto.com/vectors/glasses-set-for-water-glasses-full-empty-halffilled-with-water-vector-vector-id905957960?k=6&m=905957960&s=612x612&w=0&h=DE0uCDCehEA_eDHzHW38jvhl3pYjNuoqXZ_6ZzHbz0M=

12.4.10. Assignments

Code 12.5. Solution
"""
* Assignment: OOP Attribute Model
* Required: yes
* Complexity: easy
* Lines of code: 12 lines
* Time: 8 min

English:
    1. Modify code below
    2. Add attibutes to model the data:
       a. Watney, USA, 1969-07-21
       b. NASA, USA, 1958-07-29
    3. Create instances (watney, nasa) filling it with data
    4. Run doctests - all must succeed

Polish:
    1. Zmodyfikuj kod poniżej
    2. Dodaj atrybuty by zamodelować dane:
       a. Watney, USA, 1969-07-21
       b. NASA, USA, 1958-07-29
    3. Stwórz instancje (watney, nasa) wypełniając je danymi
    4. Uruchom doctesty - wszystkie muszą się powieść

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

    >>> assert isinstance(watney, Astronaut)
    >>> assert isinstance(nasa, SpaceAgency)
    >>> assert 'Watney' in vars(watney).values()
    >>> assert 'USA' in vars(watney).values()
    >>> assert '1969-07-21' in vars(watney).values()
    >>> assert 'NASA' in vars(nasa).values()
    >>> assert 'USA' in vars(nasa).values()
    >>> assert '1958-07-29' in vars(nasa).values()
"""


# Watney, USA, 1969-07-21
# NASA, USA, 1958-07-29

class Astronaut:
    pass


class SpaceAgency:
    pass


watney = Astronaut()
nasa = SpaceAgency()