From the course: Advanced Python: Object-Oriented Programming

Unlock the full course today

Join today to access over 24,700 courses taught by industry experts.

namedtuple()

namedtuple()

- [Instructor] In this video, we're going to talk about using namedtuple to create new classes. Namedtuple has been around for a long time. It creates a new class for you by using this function called namedtuple. Let's have a look. Let's say that I have a game. And in this game, we have rooms. Each room has an X and a Y coordinate for the middle of the room. So instead of writing a class, I'm saying Room equal namedtuple. I need to give it the name of the class, and then a list of attributes, which can be either a list of strings or a string with spaces like I'm doing here. And now I can create a room r1, which is on 1, 2, and I'm going to print it out and let's run it. And you see that we already got a wrapper written for us. So the room is represented as a string nicely. I can access attributes. So because r is a namedtuple, it inherits from tuple, there is a length to it. And I can also access X by the name or by position because it is the first attribute. The nice thing about…

Contents