Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > de.comp.lang.python > #5601
| From | Niko Wenselowski <niko@nerdno.de> |
|---|---|
| Newsgroups | de.comp.lang.python |
| Subject | Re: [Python-de] (named) Tuples und ihre Verwendung |
| Date | 2019-12-16 14:38 +0100 |
| Message-ID | <mailman.108.1576503984.11485.python-de@python.org> (permalink) |
| References | <f4baa969-3cbd-4621-a1ff-f39f4040cc31@googlegroups.com> <79faf97a-cc4e-2cd7-0f4a-a189b0e7f8a2@nerdno.de> |
Hi Patrick,
wie schon erläutert sind tuples erstmal immutable Aufzählungen.
Zur Anwendung kommen tuples oftmals dann, wenn die Daten nicht verändert
werden können / sollen.
Named tuples machen die Verwendung von Tuples einfacher, weil man zur
Adressierung der Elemente darin anstatt mittels Zugriff per Index diese
direkt wie ein Attribut ansprechen kann.
Das erleichtert erstmal das Code-Verständnis, kann aber auch eine
sinnvolle Grundlage sein, falls man später den Code mal umbauen will
(bspw. zur Verwendung von eigenen Klassen oder wenn das Python aktuell
genug ist mittels dataclasses).
Hier ist mal ein kleines Beispiel zur Arbeit mit named tuples:
from collections import namedtuple
from datetime import date
Contract = namedtuple("Contract", "nr customer expiration_date")
data = [Contract("A123", "Hans AG", date(2020, 1, 30)),
Contract("A124", "Hubert UH", date(2020, 2, 16)),
Contract("A125", "Wurst GmbH", date(2019, 12, 31))]
for contract in data:
print("Contract #%s with %s expires on %s" % contract)
if contract.expiration_date < date(2020, 1, 1):
print("ATTENTION: Contract %s will expire this year!" %
contract.nr)
Viele Grüße
Niko
Back to de.comp.lang.python | Previous | Next — Previous in thread | Find similar
(named) Tuples und ihre Verwendung Patrick Frank <patrick.frank.042@gmail.com> - 2019-12-02 11:20 -0800 Re: [Python-de] (named) Tuples und ihre Verwendung Rainer Fischbach <fischbach@ecs-gmbh.de> - 2019-12-02 20:50 +0000 Re: [Python-de] (named) Tuples und ihre Verwendung Niko Wenselowski <niko@nerdno.de> - 2019-12-16 14:38 +0100
csiph-web