python
[Python] Namedtuples can be a great alternative to defining a class manually
# 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"
Was this helpful?
Similar Posts
- [Python] Create a list of objects using class names
- Evaluate,check before class feald values set, bothe constructor,property option
- Python Measure the execution time of small bits of Python code with the timeit module
- [Python] Use json.dumps() to pretty-print Python dicts
- [Python] The get() method on Python dicts and its "default" arg
- [Python] Different ways to test multiple flags at once in Python
- Python collection - List in python