Adding a Method to an Existing Object Instance

后端 未结 16 3263
夕颜
夕颜 2020-11-21 05:45

I\'ve read that it is possible to add a method to an existing object (i.e., not in the class definition) in Python.

I understand that it\'s not always good to do so

16条回答
  •  没有蜡笔的小新
    2020-11-21 06:09

    I find it strange that nobody mentioned that all of the methods listed above creates a cycle reference between the added method and the instance, causing the object to be persistent till garbage collection. There was an old trick adding a descriptor by extending the class of the object:

    def addmethod(obj, name, func):
        klass = obj.__class__
        subclass = type(klass.__name__, (klass,), {})
        setattr(subclass, name, func)
        obj.__class__ = subclass
    

提交回复
热议问题