0

I don't understand the behavior of __call__:

class Filter:
    def __init__(self, before, after, source):
        self.filter = {}
        self.filter['before:'] = before
        self.filter['after:'] = after
        self.filter['source:'] = source

    def __call__(self):
        return ' AND '.join([key + value for key, value in self.filter.items()])

When I call the instance, __call__ is not executed:

print(Filter(before='today', after='yesterday', source='web'))

returns <__main__.Filter object at 0x103f2bf10>

while

print(Filter(before='today', after='yesterday', source='web').__call__())

does what I want and returns what is defined in __call__(): before:today AND after:yesterday AND source:web

Why is this happening? Do I need to create an empty object first, then instantiate it, to make __call__ work?

martineau
  • 119,623
  • 25
  • 170
  • 301
Zin Yosrim
  • 1,602
  • 1
  • 22
  • 40
  • `Filter(before='today', after='yesterday', source='web')` doesn't call the instance, it calls the constructor, `Filter`. Calling the instance would be `Filter(before='today', after='yesterday', source='web')()` although this seems like a very strange use of the `__call__` dunder method... – juanpa.arrivillaga Dec 31 '19 at 14:32

2 Answers2

2

Filter(...) does not "call" the instance, it creates it. To call, use the call syntax on the resulting object:

>>> Filter(...)()

or

>>> filt = Filter(...)
>>> filt()
Seb
  • 4,422
  • 14
  • 23
2

In Filter(before='today', after='yesterday', source='web'), you don't call an instance, you create one. When you print it, you get the default representation for an instance of class Filter: <__main__.Filter object at 0x103f2bf10>

You need to create the instance first, then call it:

filter = Filter(before='today', after='yesterday', source='web')
filter()

Output:

'before:today AND after:yesterday AND source:web'

There is no need to explicitely use <your instance>.__call__(), just use the parentheses like you would do for any function.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50