【发布时间】:2018-11-11 05:10:19
【问题描述】:
编辑:很遗憾,What is the difference between __init__ and __call__ in Python? 没有回答这个问题
class OAuth2Bearer(requests.auth.AuthBase):
def __init__(self, api_key, access_token):
self._api_key = api_key
self._access_token = access_token
def __call__(self, r):
r.headers['Api-Key'] = self._api_key
r.headers['Authorization'] = "Bearer {}".format(self._access_token)
return r
#############
class AllegroAuthHandler(object):
def apply_auth(self):
return OAuth2Bearer(self._api_key, self.access_token) # what will happen here?
我读到了 __init__ 和 __call__,但我仍然不明白这段代码中发生了什么
我不明白:
1.) 将调用哪个方法,__init__ 或 __call__
2.) 如果__init__,那么__init__ 不会返回任何内容
3.) 如果__call__,则__call__不能用两个参数调用
我认为应该调用__init__,因为我们有X(),而不是下面示例中的x(),如this answer:
x = X() # __init__ (constructor)
x() # __call__
【问题讨论】:
-
@SeverinPappadeux 不幸的是,这并不能解释问题 2 和 3 :-(
-
@Sid 不幸的是,这并不能解释问题 2 和 3 :-(
-
你说得对,
__init__没有返回任何东西,但它在新对象上调用,这是你调用类时返回的东西。所以你可以想象一个return self,你或多或少会有一个正确的想法。
标签: python class constructor call init