teaching:progappchim:collection_namedtuple_exemple

no way to compare when less than two revisions

Différences

Ci-dessous, les différences entre deux révisions de la page.


Prochaine révision
teaching:progappchim:collection_namedtuple_exemple [2016/11/29 12:31] – créée villersd
Ligne 1: Ligne 1:
 +====== Exemple d'utilisation de namedtuple ======
 +
 +L'utilisation de namedtuple peut s'avérer plus rapide que la définition de classes (objets)
 +
 +
 +<sxh python; title : namedtuple-chemical_elements-01.py>
 +#!/usr/bin/env python
 +# -*- coding: utf-8 -*-
 +
 +from collections import namedtuple
 +
 +ChemEl = namedtuple('Element', 'name atomic_number symbol group period atomic_weight')
 +# same as defining a class for elements 
 +
 +hydrogen = ChemEl('hydrogen', 1, 'H', 1, 1, 1.008)
 +helium = ChemEl('helium', 2, 'He', 18, 1, 4.002602)
 +
 +print(hydrogen.atomic_weight)
 +print(hydrogen.symbol)
 +
 +print(hydrogen, type(hydrogen))
 +print(helium)
 +
 +</sxh>
 +
 +===== Références =====
 +Module collections :
 +  * [[https://docs.python.org/2/library/collections.html]]
 +  * [[https://docs.python.org/3/library/collections.html]]
 +  * [[https://docs.python.org/3/library/collections.html#collections.namedtuple]]
 +
  
  • teaching/progappchim/collection_namedtuple_exemple.txt
  • Dernière modification : 2021/01/22 11:33
  • de villersd