Skip to content

Instantly share code, notes, and snippets.

@penn201500
Created August 29, 2017 09:54
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save penn201500/21f537ec67c8e7c01ca69dcfc20373a3 to your computer and use it in GitHub Desktop.
nametuple_instead_of_class
# Why Python is Great: Namedtuples
# Using namedtuple is way shorter than
# defining a class manually:
>>> from collections import namedtuple
>>> Car = namedtup1e('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"
@penn201500
Copy link
Author

for python

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment