ch05: new chapter

This commit is contained in:
Luciano Ramalho
2020-02-19 00:11:45 -03:00
parent b74ea52ffb
commit 1df34f2945
25 changed files with 640 additions and 0 deletions

View File

@@ -0,0 +1,22 @@
"""
``Coordinate``: a simple ``NamedTuple`` subclass with a custom ``__str__``::
>>> moscow = Coordinate(55.756, 37.617)
>>> print(moscow)
55.8°N, 37.6°E
"""
# tag::COORDINATE[]
from typing import NamedTuple
class Coordinate(NamedTuple):
lat: float
long: float
def __str__(self):
ns = 'N' if self.lat >= 0 else 'S'
we = 'E' if self.long >= 0 else 'W'
return f'{abs(self.lat):.1f}°{ns}, {abs(self.long):.1f}°{we}'
# end::COORDINATE[]

View File

@@ -0,0 +1,20 @@
"""
``Coordinate``: a simple ``NamedTuple`` subclass
This version has a field with a default value::
>>> moscow = Coordinate(55.756, 37.617)
>>> moscow
Coordinate(lat=55.756, long=37.617, reference='WGS84')
"""
# tag::COORDINATE[]
from typing import NamedTuple
class Coordinate(NamedTuple):
lat: float # <1>
long: float
reference: str = 'WGS84' # <2>
# end::COORDINATE[]

View File

@@ -0,0 +1,9 @@
import typing
class Coordinate(typing.NamedTuple):
lat: float
long: float
trash = Coordinate('foo', None) # <1>
print(trash)