What is the difference between class(namedtuple) and only namedtuple, they look different but in both cases sensor seems to be the same thing, and what kind of functionality can be added inside class Sensor in case1?
from collections import namedtuple
# case 1
class Sensor(namedtuple('Sensor', ['name', 'location', 'version', 'pressure', 'temperature'])):
pass
sensor = Sensor(name="example", location="warehouse_125", version="1", pressure=128, temperature=10)
# case 2
Sensor = namedtuple('Sensor', ['name', 'location', 'version', 'pressure', 'temperature'])
sensor = Sensor(name="example", location="warehouse_125", version="1", pressure=128, temperature=10)
You should know that
collections.namedtupleis a factory function. It returns a subclass of a tuple which is gonna be your actual class.So by doing:
You're subclassing this newly created namedtuple class. Just like:
This is extending/subclassing another class, you can add whatever you want. But in "case 2",
Sensoris only a name/symbol which is bound to the actual namedtuple class.The inheritance chain would be:
For example you can have a method call
.store()which add this namedtuple object to a database. Or maybe you can have a property which says the weather in the location of the sensor is cold or hot?These
.store()and.weatherwere not innamedtupleclass. You extend it and give them extra functionality.