changing the class of a python object (casting)

后端 未结 4 1881
滥情空心
滥情空心 2020-12-01 13:44

On this python doc page it says:

Like its identity, an object’s type is also unchangeable.

And I try this script,

<         


        
4条回答
  •  爱一瞬间的悲伤
    2020-12-01 14:29

    I was asked this question by a colleague today. He had a parent class that wanted to promote itself automatically to be one of its children based on an input at init time. The following script worked as a proof of concept:

    class ClassB(object):
    
        def __init__(self):
            self.__class__ = ClassA
    
        def blah2(self,t):
            print('I give you',t)
            return 'You are welcome'
    
    class ClassA(ClassB):
    
       def blah(self, t):
           print('you gave me',t)
           return 'Thankyou'
    
    
    
    a = ClassB()
    print(type(a))
    print(a.blah('sausage'))
    print(a.blah2('cabbage'))
    

    The result shows:

    
    you gave me sausage
    Thankyou
    I give you cabbage
    You are welcome
    

    Which shows that both the parent and child functions are now available to A.

提交回复
热议问题