Adding a Method to an Existing Object Instance

后端 未结 16 2965
夕颜
夕颜 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 05:57

    Module new is deprecated since python 2.6 and removed in 3.0, use types

    see http://docs.python.org/library/new.html

    In the example below I've deliberately removed return value from patch_me() function. I think that giving return value may make one believe that patch returns a new object, which is not true - it modifies the incoming one. Probably this can facilitate a more disciplined use of monkeypatching.

    import types
    
    class A(object):#but seems to work for old style objects too
        pass
    
    def patch_me(target):
        def method(target,x):
            print "x=",x
            print "called from", target
        target.method = types.MethodType(method,target)
        #add more if needed
    
    a = A()
    print a
    #out: <__main__.A object at 0x2b73ac88bfd0>  
    patch_me(a)    #patch instance
    a.method(5)
    #out: x= 5
    #out: called from <__main__.A object at 0x2b73ac88bfd0>
    patch_me(A)
    A.method(6)        #can patch class too
    #out: x= 6
    #out: called from 
    

提交回复
热议问题