-1

My lecturer wrote some code and I have no idea how to read it and google isn't helping, can someone please clarify how this code interacts.

yield Arc(tail_node, head = tail_node - 1, label="1down", cost=1)

Is the method call for the class

class Arc(namedtuple('Arc', 'tail, head, label, cost')):

The class Arc contains no methods, and no __init. I have no clue how these two are interacting since I thought class parameters accepted another class, and it made the current class a subclass or abstract etc.

1 Answers1

0

The collections.namedtuple function is a class factory. It takes some parameters and returns a class. The class inherits from tuple, but its values are also accessible by name as attributes (not only by index).

The Arc class you show uses namedtuple to create its base class. You could equivalently write it with separate statements, giving the base class it's own name:

Base = namedtuple('Arc', 'tail, head, label, cost')   # this creates a class
class Arc(Base):    # this class inherits from the base class
    pass

If the Arc class doesn't have any methods of its own, there wouldn't be much point in defining it at all (you'd just use the name Arc instead of Base for the class returned from namedtuple). I'm guessing there is some more code in the Arc class, just not anything relevant to your question. The behavior inherited from the base class is enough to create instances using positional or keyword arguments, so the yield statement you show doesn't need any additional code.

Blckknght
  • 100,903
  • 11
  • 120
  • 169