default values for namedtuple

Asked

Viewed 61 times

2

When creating a class I can set some default values:

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

How to proceed the same way for namedtuple?

from collection import namedtuple
Point = namedtuple('Point', 'x, y, z')

2 answers

1

No python3 use .__new__.__defaults__ to assign default values.

Points = namedtuple('Points', 'x y z')
Points.__new__.__defaults__ = (None,None,'Foo')
Points()
Points(x=None, y=None, z='Foo')
  • That’s what I want. Thanks. But you can set value to z only?

  • I don’t think so, but it doesn’t serve to define others as None?

1

Subclass the result of namedtuple and rewrites the value of __new__ as follows:

from collections import namedtuple
class Move(namedtuple('Point', 'x, y, z')):
    def __new__(nome, piece, start, to, captured=None, promotion=None):
        # adicionar valores padrao
        return super(Point, nome).__new__(nome, x, y, z=0)
  • has some way of doing so without declaring a new class?

  • In the test I noticed that the Move class inherits from the Point class, I want to create the Point with namedtuple, and put z as default value.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.