Home >Backend Development >Python Tutorial >Named Tuples in Python: what type are they?

Named Tuples in Python: what type are they?

DDD
DDDOriginal
2024-11-23 05:31:24891browse

Named Tuples in Python: what type are they?

Named tuples in Python are an extension of the built-in tuple data type, allowing you to give meaningful names to the elements of a tuple. In others words, named tuples are tuples with named attributes. Isn't that cool?

They are part of the collections module and provide a way to define simple, immutable classes in a simpler way.

Wait what, classes?
Yes, classes.

Named tuples are essentially immutable classes.

This is the magic that occurs: when you create a named tuple using namedtuple, the result is not an instance of the tuple itself, but rather a dynamically generated class that inherits from tuple. Again, cool!!

Let's see how this works.

from collections import namedtuple 

P = namedtuple("Point", "x y")

When you run P = namedtuple("Point", "x y"), you are creating a new class named Point (as specified in the first argument to namedtuple).

The namedtuple function uses type behind the scenes to dynamically create a new class named Point that inherits from tuple. This new class is stored in the variable P.

And as with classes, the type is type.

> type(P)
class 'type'
> class A:
    pass

> type(A)
class 'type'

And what type is the instance of a namedtuple?

from collections import namedtuple 

P = namedtuple("Point", "x y")
p = P(1,2)

> print(type(p)) 
class '__main__.Point'

p is an instance of type Point. But it's also a tuple:

> print(isinstance(p, tuple))
True

In summary:

  • P is a class generated dynamically by namedtuple.
  • Instances of P are objects of type Point that also subclass tuple.

And one last thing:

It's very common to name the namedtuple variable (what we called P) with the same name as the type name (what we called Point), the dynamically created class:

from collections import namedtuple 

Point = namedtuple("Point", "x y")

I used a different name to make clear the distinction between thw two.

The above is the detailed content of Named Tuples in Python: what type are they?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn