From the course: Python Object-Oriented Programming
Unlock the full course today
Join today to access over 24,500 courses taught by industry experts.
Callable objects - Python Tutorial
From the course: Python Object-Oriented Programming
Callable objects
- [Instructor] To finish up this chapter, we'll take a look at the magic method that enables Python objects to be callable, just like any other function. Now, that might sound a little bit weird but it's easy to understand it when you see it in action. So let's open up the example code in magiccall_start. And you can see that once again, I've got my Book class and it's already implementing the str function that we learned about earlier. And I also have some code that creates a couple of book instances with titles and authors and prices. So what I'm going to do is override the __call function that lets me treat an instance of the object, like a function and I'll define the function to take the same parameters as the init function. You can also define the function to take a variable number of arguments, but that's a little more advanced. And I want to focus here on the feature itself. So what I'm going to do is add a function…