How do you cast an instance to a derived class?

前端 未结 5 1901

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

    class A:
     def __init__(self, variable):
        self.a = 10
        self.a_variable = variable
    
     def do_something(self):
        print("do something A")
    
    
    class B(A):
    
     def __init__(self, variable=None):
        super().__init__(variable)
        self.b = 15
    
     @classmethod
     def from_A(cls, a: A):
        # Create new b_obj
        b_obj = cls()
        # Copy all values of A to B
        # It does not have any problem since they have common template
        for key, value in a.__dict__.items():
            b_obj.__dict__[key] = value
        return b_obj
    
    if __name__ == "__main__":
     a = A(variable="something")
     b = B.from_A(a=a)
     print(a.__dict__)
     print(b.__dict__)
     b.do_something()
     print(type(b))
    

    Result:

    {'a': 10, 'a_variable': 'something'}
    {'a': 10, 'a_variable': 'something', 'b': 15}
    do something A
    
    

提交回复
热议问题