Question

I have the following code

import numpy as np

class Estimator(object):
    name = None

    def __init__(self):
        self.__call__ = self._call

class Mean(Estimator):
    name = 'mean'

    def _call(self, data):
        return np.mean(data)

data = np.arange(10)

now, why I can't use the second class as a functor as the first?

It seems to work:

M = Mean()
print M.__call__(data)  # -> 4.5

M has the method __call__:

print '__call__' in dir(M)  # -> True

but it doesn't work

print M(data)

I get:

TypeError: 'Mean' object is not callable
Was it helpful?

Solution

As Ashwini says, "Special methods are looked up in class not instances".

So the following would work as you expect (although I can't imagine why you would want to):

class Estimator(object):
    name = None

    def __init__(self):
        self.__class__.__call__ = self.__class__._call

class Mean(Estimator):
    name = 'mean'

    def _call(self, data):
        return np.mean(data)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top