How to change "namedtuples" into classes in Python?

python

Solution

The return value of `namedtuple` is a class. No dark magic. You do not need to "convert" a namedtuple return into a class; it returned exactly that.

`namedtuple` creates a new class that inherits from `__builtin__.tuple`. When you call `namedtuple('Point', 'x y')(1, 0)`, you're getting is the tuple object `(1, 0)` with the following syntactic sugar:

- a `__dict__` mapping where `{'x': 1, 'y', 0}`

- two properties `x` and `y` that call `__getitem__(0)` and `__getitem__(1)` respectively.

- a `__repr__` method that returns `'Point(x=1, y=0)'`

Other than this, it's just a tuple object. Its attributes and number of attributes are immutable.

However, I suspect you mean you want to take `nametuple('Point', 'x, y')` and instead get:

class Point:
    def __init__(x, y):
        self.x = x
        self.y = y

In this case you are misusing `nametuple`, and should instead be using `type`:

def init(self, x, y):
    self.x, self.y = x, y
Point = type('Point', (object,), {'__init__': init})

Problem

Can anyone give an example? What's the difference between using variables in classes and in namedtuples?

Original source