Programmer's Python - Inside Class |
Written by Mike James | |||
Monday, 10 December 2018 | |||
Page 2 of 2
SingletonFinal version in book Customizing Immutable Data ObjectsFinal version in book How Instances Become FunctionsThe final question we have to answer is how is it that we can call a class as if it was a function? The answer is that there is a magic __call__ method and any object which has it defined can be called like a function – it is a callable. This is the basic idea but there is a subtle extra condition. The __call__ has to be defined on the object’s class object. The Python documentation says that magic methods aren’t guaranteed to work if they are defined on the object rather than its class. This is the case for __call__. If you want an object to be callable you have to define __call__ on its class. For example: class MyClass: def __call__(self,*args, **kwargs): print("class call") If you now create an instance it can be called like a function: myObject=MyClass() myObject() and you will see “class call” printed. Being able to create an instance that is a function is very useful but notice that as it is the class __call__ method that is actually called, all of the instances of a class are restricted to use the same function. This is usually a reasonable way to organize things. In general adding methods of any kind to an instance is not best practice. To modify the way an instance works the best option is to create a subclass i.e. use inheritance and override the methods you want to change - see Chapter 11. See the next chapter to discover how class objects become callable. Summary
Programmer's Python
|
|||
Last Updated ( Monday, 10 December 2018 ) |