How do you cast an instance to a derived class?

前端 未结 5 1886

I am trying to use a little inheritance in a Python program I am working on. I have a base class, User, which implements all of the functionality of a user. I am adding the co

5条回答
  •  广开言路
    2021-02-13 23:33

    Rather than "casting", I think you really want to create an UnapprovedUser rather than a User when invoking UnapprovedUser.get(). To do that:

    Change User.get to actually use the cls argument that's passed-in:

    @classmethod
    def get(cls, uid):
        ldap_data = LdapUtil.get(uid + ',' + self.base_dn)
        return cls._from_ldap(ldap_data)
    

    You'll need to do something similar in _from_ldap. You didn't list the code for _from_ldap, but I assume that at some point it does something like:

    result = User(... blah ...)
    

    You want to replace this with:

    result = cls(... blah ...)
    

    Remember: in Python a class object is a callable that constructs instances of that class. So you can use the cls parameter of a classmethod to construct instances of the class used to call the classmethod.

提交回复
热议问题