Reclassing an instance in Python

前端 未结 8 584
野趣味
野趣味 2020-12-02 10:07

I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class.

I now want to t

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 10:21

    "The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change it's class." - Head First Design Pattern. Something very similar write Gamma et.al. in their Design Patterns book. (I have it at my other place, so no quote). I think that's the whole point of this design pattern. But if I can change the class of an object at runtime, most of the time i don't need the pattern (there are cases when State Pattern does more than simulate a class change).

    Also, changing class at runtime doesn't always work:

    class A(object):
        def __init__(self, val):
            self.val = val
        def get_val(self):
            return self.val
    
    class B(A):
        def __init__(self, val1, val2):
            A.__init__(self, val1)
            self.val2 = val2
        def get_val(self):
            return self.val + self.val2
    
    
    a = A(3)
    b = B(4, 6)
    
    print a.get_val()
    print b.get_val()
    
    a.__class__ = B
    
    print a.get_val() # oops!
    

    Apart from that, I consider changing class at runtime Pythonic and use it from time to time.

提交回复
热议问题