Home > Software engineering >  Difference between a class(namedtuple) and a namedtuple
Difference between a class(namedtuple) and a namedtuple

Time:12-20

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)

CodePudding user response:

You should know that collections.namedtuple is a factory function. It returns a subclass of a tuple which is gonna be your actual class.

So by doing:

class Sensor(namedtuple('Sensor', ['name', 'location', 'version', 'pressure', 'temperature'])):
    pass

You're subclassing this newly created namedtuple class. Just like:

class Sensor(<another_class>):
    pass

what kind of function/code can be added inside class Sensor in case1?

This is extending/subclassing another class, you can add whatever you want. But in "case 2", Sensor is only a name/symbol which is bound to the actual namedtuple class.

The inheritance chain would be:

#case 1
object > tuple > namedtuple class(without attached symbol) > Sensor

#case 2
object > tuple > namedtuple class(Sensor)

but can you give some example that I can add inside class Sensor? to show there is an use case or advantage of using class Sensor?

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?

from collections import namedtuple


class Sensor(namedtuple("Sensor", ["name", "location", "temperature"])):
    def store(self):
        """Add this object to the DataBase"""
        print("Adding to the database...")
        # Make a connection to the database
        # INSERT INTO ....

    @property
    def weather(self):
        if self.temperature > 30:
            return "Hot"
        if 10 < self.temperature <= 30:
            return "Moderate"
        if self.temperature <= 10:
            return "Cold"


sensor_1 = Sensor("A1", "warehouse125", 20)
sensor_1.store()
print(f"The weather is {sensor_1.weather}")

These .store() and .weather were not in namedtuple class. You extend it and give them extra functionality.

  • Related