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 concept of an unapproved user, which is just like a user, with the addition of a single method.
The User class has some methods that return a User object. This will not work when I subclass, since I will end up having an UnapprovedUser return a User, preventing me from calling this method, among other things.
class User(object):
base_dn = 'ou=Users,dc=example,dc=org'
@classmethod
def get(cls, uid):
ldap_data = LdapUtil.get(uid + ',' + self.base_dn)
return User._from_ldap(ldap_data)
class UnapprovedUser(User):
base_dn = 'ou=UnapprovedUsers,dc=example,dc=org'
def approve(self):
new_dn = '' # the new DN
LdapUtil.move(self.dn, new_dn)
The get()
and _from_ldap()
methods are the same for both classes, though the get()
method in UnapprovedUser needs to return an UnapprovedUser object, not a User.
How can I cast one of the instances of User that I get from User.get()
into an UnapprovedUser?
I want to do something like:
class UnapprovedUser(User):
# continued from before
@classmethod
def get(cls, uid):
user = super(UnapprovedUser, cls).get(uid)
return (UnapprovedUser) user # invalid syntax
so that I can wrap the method from the parent and simply cast the returned value to the correct class. Then again, doing it that way could lead to the parent using their value for self.base_dn
, which would break everything.