How do you cast an instance to a derived class?

In a class method, the class is passed in in the cls parameter. So instead of User.something do cls.something. Done!

That said, I'm not sure I would do this with two types of user. I'm not 100% sure what you mean with "Approved" here, I it seems to me to be one of two things.

  1. It may mean the user isn't really logged in yet. In that case I'd have a special Anonymous User instance for not logged in users. Since you are moving the DN when approving, this seems more likely to be what you are doing.

  2. It may mean that the user hasn't been approved as a full member or something. This is just a special case of permission handling, and you are probably going to end up wanting to have more permissions later. I'd instead add support for giving the user roles, and making "Approved" a role.

If you mean something else with approved, feel free to ignore this. :-)


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.