python – How do you cast an instance to a derived class?

python – How do you cast an instance to a derived class?

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 thats passed-in:

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

Youll need to do something similar in _from_ldap. You didnt 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.

Python is a dynamically-typed language, so the concept of casting doesnt exist. If the object is already an UnapprovedUser, then you can already call all methods that exist in that class, without having to cast.

python – 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, Im not sure I would do this with two types of user. Im 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 isnt really logged in yet. In that case Id 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 hasnt 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. Id 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. 🙂

Leave a Reply

Your email address will not be published.