1

可能重复:python中的initcall
有什么区别?

我正在尝试创建一个可调用的类,该类将接受参数,然后将自身作为对象返回。

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):
4

1 回答 1

4

__call__ is only called on an instance that defines itself as callable.

__init__ is the initializer that provided an instance of the class

If you do something like

MyObject()() Then you are initliaizing THEN calling.

Using your own example

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.
于 2012-09-23T17:14:58.520 回答