Last active
November 15, 2018 15:35
-
-
Save arzon94/d4c8a0cbabc690557bacbd8d89b2fadb to your computer and use it in GitHub Desktop.
tuples/named tuples are immutable, quick way of making a class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Why Python is Great: Namedtuples | |
| # Using namedtuple is way shorter than | |
| # defining a class manually: | |
| >>> from collections import namedtuple | |
| >>> Car = namedtuple('Car', 'color mileage') | |
| # Our new "Car" class works as expected: | |
| >>> my_car = Car('red', 3812.4) | |
| >>> my_car.color | |
| 'red' | |
| >>> my_car.mileage | |
| 3812.4 | |
| # We get a nice string repr for free: | |
| >>> my_car | |
| Car(color='red' , mileage=3812.4) | |
| # Like tuples, namedtuples are immutable: | |
| >>> my_car.color = 'blue' | |
| AttributeError: "can't set attribute" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment