changing the class of a python object (casting)

后端 未结 4 1862
滥情空心
滥情空心 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:33

    Old question but here's a technique for safely extending the type of a python object.

    def extendObject(obj):
        # Our extended type is explicitly derived from our existing type.
        class Extended(obj.__class__):
            # Whatever extensions you want to make.
            def someMethod(self):
                pass
        # Change the type of the object.
        obj.__class__ = Extended
        return obj
    

提交回复
热议问题