我想知道__init__和__call__方法之间的区别。

例如:

class test:

  def __init__(self):
    self.a = 10

  def __call__(self): 
    b = 20

当前回答

案例1:

class Example:
    def __init__(self, a, b, c):
        self.a=a
        self.b=b
        self.c=c
        print("init", self.a, self.b, self.c)

Run:

Example(1,2,3)(7,8,9)

结果:

- init 1 2 3
- TypeError: 'Example' object is not callable

案例2:

class Example:
    def __init__(self, a, b, c):
        self.a=a
        self.b=b
        self.c=c
        print("init", self.a, self.b, self.c)
    def __call__(self, x, y, z):
        self.x=x
        self.y=y
        self.z=z
        print("call", self.x, self.y, self.z)

Run:

Example(1,2,3)(7,8,9)

结果:

- init 1 2 3
- call 7 8 9

其他回答

__call__使类的实例可调用。 为什么需要它?

从技术上讲,__init__在对象创建时由__new__调用一次,以便可以初始化它。

但是在许多情况下,您可能想要重新定义对象,例如您已经完成了对象,并且可能发现需要一个新对象。使用__call__,你可以重新定义相同的对象,就像它是新的一样。

这只是一个案例,可能还有更多。

第一个用于初始化新创建的对象,并接收用于初始化的参数:

class Foo:
    def __init__(self, a, b, c):
        # ...

x = Foo(1, 2, 3) # __init__

第二部分实现函数调用操作符。

class Foo:
    def __call__(self, a, b, c):
        # ...

x = Foo()
x(1, 2, 3) # __call__
>>> class A:
...     def __init__(self):
...         print "From init ... "
... 
>>> a = A()
From init ... 
>>> a()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: A instance has no __call__ method
>>> 
>>> class B:
...     def __init__(self):
...         print "From init ... "
...     def __call__(self):
...         print "From call ... "
... 
>>> b = B()
From init ... 
>>> b()
From call ... 
>>> 

我们可以使用调用方法来使用其他类方法作为静态方法。

class _Callable:
    def __init__(self, anycallable):
        self.__call__ = anycallable

class Model:

    def get_instance(conn, table_name):

        """ do something"""

    get_instance = _Callable(get_instance)

provs_fac = Model.get_instance(connection, "users")  

方法用于使对象像函数一样工作。

>>> class A:
...     def __init__(self):
...         print "From init ... "
... 
>>> a = A()
From init ... 
>>> a()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: A instance has no __call__ method

<*There is no __call__ method so it doesn't act like function and throws error.*>

>>> 
>>> class B:
...     def __init__(self):
...         print "From init ... "
...     def __call__(self):
...         print "From call it is a function ... "
... 
>>> b = B()
From init ... 
>>> b()
From call it is a function... 
>>> 

<* __call__ method made object "b" to act like function *>

我们也可以把它传递给一个类变量。

class B:
    a = A()
    def __init__(self):
       print "From init ... "