How do you cast an instance to a derived class?

前端 未结 5 1893

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:32

    • super(UnapprovedUser, self) is wrong it should be super(UnapprovedUser, cls) because in class method you do not have self available

    • I will reiterate your question , in base class you are creating user and somehow you want to return derived class e.g.

    
       class User(object):
    
           @classmethod
           def get(cls, uid):
               return User()
    
       class UnapprovedUser(User):
    
           @classmethod
           def get(cls, uid):
               user = super(UnapprovedUser, cls).get(uid)
               return user # invalid syntax
    
       print UnapprovedUser.get("XXX")
    

    it prints User object instead of UnapprovedUser object here you want UnapprovedUser.get to return UnapprovedUser, for that you can create a factory function which wil return appropriate user and than fill it with ldap

    
        class User(object):
    
            @classmethod
            def get(cls, uid):
                return cls.getMe()
    
            @classmethod
            def getMe(cls):
                return cls()
    
        class UnapprovedUser(User):
    
            @classmethod
            def get(cls, uid):
                user = super(UnapprovedUser, cls).get(uid)
                return user 
    
        print UnapprovedUser.get("XXX")
    

    it prints UnapprovedUser object

提交回复
热议问题