__call__ vs. __init__: Who gets the arguments? Who gets called first?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
what is difference between init and call in python?
我正在尝试创建一个可调用类,它将接受参数,然后将自身作为对象返回。
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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 |
我的问题是,如果我这样称呼这个对象:
1 | newUserObject = User(submittedLoginName) |
会在
1 | def __call__(self, loginName): |
仅对定义自身为可调用的实例调用
如果你做类似的事
那么你先开始联络,然后打电话。
用你自己的例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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. |