Possible Duplicate:
what is difference between init and call in python?
我正在尝试创建一个可调用类,该类将带有参数,然后将自身作为对象返回。
class User(object):
def __init__(self, loginName, password):
self.loginName = loginName
def __call__(self):
if self.login():
return self
return None
def login(self):
database = db.connection
realUser = database.checkPassWord(self.loginName, self.password)
return realUser
我的问题是,如果我这样调用该对象:
newUserObject = User(submittedLoginName)
__init__
会在__call__
之前被称为吗? __init__
应该获取参数还是我应该将参数移至__call__
?def __call__(self, loginName):
最佳答案
仅在将自身定义为可调用的实例上调用__call__
。__init__
是提供类实例的初始化程序
如果你做类似的事情MyObject()()
然后您要初始化THEN调用。
用你自己的例子
class User(object):
def __init__(self, loginName, password):
self.loginName = loginName
self.password = password
def __call__(self):
if self.login():
return self
return None
def login(self):
database = db.connection
return database.checkPassWord(self.loginName, self.password)
a = User("me", "mypassword")
a = a() # a is now either None or an instance that is aparantly logged in.
关于python - __call__与__init__:谁得到论点?谁先被打来? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12554397/