-2

In 8.3. collections — Container datatypes — Python 3.6.4rc1 documentation, it specify 5 methods of namedtuple.

namedtuple_methods = {'_fields', '_make', '_replace', '_asdict', '_source'}

Nevertheless, the methods cannot be acquired by dir method

from collections import namedtuple
set(dir(namedtuple)) & namedtuple_methods
In [64]: set(dir(namedtuple)) & namedtuple_methods
Out[64]: set()

They share no intersection.

Interestingly, a particular namedtuple lists the methods

Book = namedtuple('Book', 'name, author')
In [70]: set(dir(Book)) & namedtuple_methods
Out[70]: {'_asdict', '_fields', '_make', '_replace', '_source'}

What's the mechanism behind?

1 Answer 1

1

In Python, classes are objects. And namedtuple is a function that creates classes. So you have to distinguish between:

  • the namedtuple factory function. This is a function that returns a class, which is also an object.
  • a namedtuple class, for example Book = namedtuple('Book', ['name', 'author'])
  • an instance of a namedtuple class, for example Book('Brave New World', 'Aldous Huxley')

All of these are different objects. The dir() function tries to find the fields (which may be methods) that you can access on that object. So on a class object it will give you the methods and fields in that class. These methods may be class methods or instance methods, depending on their “descriptors”. In particular, dir(namedtuple) will list the fields of any function object.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.