________在Python中的行为[重复]

问题描述 投票:0回答:1

我不了解__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()])

当我调用实例时,未执行__call__

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

返回<__main__.Filter object at 0x103f2bf10>

while

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

执行我想要的并返回__call__()中定义的内容:before:today AND after:yesterday AND source:web

为什么会这样?我需要先创建一个空对象,然后实例化它,以使__call__工作吗?

python python-3.7
1个回答
1
投票

Filter(...)不会“调用”实例,而是创建实例。要调用,请在结果对象上使用调用语法:

>>> Filter(...)()

>>> filt = Filter(...)
>>> filt()

1
投票

Filter(before='today', after='yesterday', source='web')中,您不调用实例,而是创建一个实例。当您使用print时,将获得类Filter的实例的默认表示形式:<__main__.Filter object at 0x103f2bf10>

您需要先创建实例,然后调用它:

filter = Filter(before='today', after='yesterday', source='web')
filter()
© www.soinside.com 2019 - 2024. All rights reserved.